Data Driven Testing with Spock Framework

What is Spock Framework?

It is an open source Unit Testing framework for Java and Groovy based applications. It is a highly expressive testing framework.

Why should we use ?

  • More expressive tests.
  • No unnecessary annotations and no assert statements.
  • Easy to understand.

Spock Terminologies:

given: It is the block where data initialisation is done.

when: It is the block where methods are invoked and results are assigned.

then: It is the block in which results obtained from when are compared.

cleanup: It is optional and does clean up of the fields not needed.

where: It can be used to provide the data.

expect: It is a combination of when and then.

The allowed usage are in the format:

{given, when, then, cleanup, where}  OR

{given, expect, cleanup where}

How can the input and the output be provided in spock?

a) where clause is used to provide the input as well as output.

b) Input and output can be provided using data tables or data pipes.

For example:

Data tables  for an addition test is of the format:

where:

 a   |  b  | result
 5   |  6  |  11
 7   |  7  |  14

Data pipes for an addition test is of the format:

where:

 a << [5, 7]
 b << [6, 7]
result << [11, 14]

 

What are the fixture Methods in Spock?

Fixture methods in spock are as follows:

a) setup() This method is same as @Before annotation in Junit. The code written in this method will be executed before each feature method.

b) cleanup() This method is same as @After annotation in Junit. The code written in this method will be executed after each feature method.

c) setupSpec() This method is same as @BeforeClass in Junit. It is used to create the object before the start of the tests.

c) cleanupSpec() This method is same as @AfterClass in Junit. It is used to cleanup the object that were created. This is done at the end of the test execution.

Advantages of Spock

a) Quite easy and powerful

b) Bettor Error detection capability using @unroll annotation.

b) Compatible with IDE’s

Disadvantages of Spock

a) Mocking can be done with Spec Class

The code for testing using Spocks Framework can be seen here:

https://github.com/lakshay13/SpockFramework/blob/master/SpockProject/src/main/java/spockbasics/MathOperations.java

References:

http://spockframework.org/spock/docs/

 

Advertisements

One thought on “Data Driven Testing with Spock Framework

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s