Month: April 2017

Spock Framework with Groovy Example

Posted on

Spock is a testing and specification framework for Java and Groovy application.

http://spockframework.org/

 

Spock Framework with Groovy Example:-

Spock Framework gives you a highly expressive test cases in you test module. It is inspired from several existing testing framework like JUnit, RSpec, jMock, Mockito, Groovy, Scala, Vulcans.

Before starting Spock Framework in your project, you should have at least basic knowledge of Groovy, It’s not very hard to learn even it similar to Java – [ What is Groovy ].

Let start with Spock Specification which describes expected features ( Properties, Aspect ) . A Specification represented by Groovy Class that extends from import spock.lang.Specification. 

Class Specification contains a number of useful methods for writing specifications.

As JUnit, Spock also provides some predefined method for setup and cleanup method as given below:-

def setup() {}          // run before every feature method
def cleanup() {}        // run after every feature method
def setupSpec() {}     // run before the first feature method
def cleanupSpec() {}   // run after the last feature method

@shared:

Sometimes an object needs to be shared between features methods rather than creating it every time in features method level which may be expensive to recreate every time. so we need to share that object between features therefore, @Shared  annotation helps us to do this job.

Objects stored into instance fields are not shared between feature methods. Instead, every feature method gets its own object. This helps to isolate feature methods from each other, which is often a desirable goal.

@shared
def connection = new DBConnection();

Block : –

Block is a predefined set of a label that supported by Spock Framework. Usually, Block is an area where a setup, stimulus, response, condition, expectation and cleanup is described.

Blocks2Phases

below are the complete example of Spock specification that would help us to understand.

@Unroll :-

As you can see in below Spock Test example, @Unroll annotation are used in some features, By putting @Unroll annotation on the feature. it means an iteration is required on feature and on each iteration values given in where block get substituted by its value and leading hash sign (#), to refer to data variables.

@Unroll
def "Power(#base,#exponent) == #result1 and Power(#base,2) == #result2"() {
    expect:
    Math.pow(base, exponent) == result1
    and:
    Math.pow(base, 2) == result2
    where:
    base | exponent || result1 | result2
    1    | 2        || 1 | 1
    2    | 3        || 8 | 4
    3    | 4        || 81 | 9
    4    | 5        || 1024 | 16
}

Prerequisites

  • JDK 5 or higher
  • Ant 1.7 or higher (for Ant build)
  • Maven 2.x (for Maven build)

Creating an IDEA Project:-

  • Create a Java project in IntellJ and set up project source folder and testing source folder under the project.

 

 

 

 

 

 

 

  • Create a pom.xml file under root folder and copy and paste below contents and build this project by command line or IntelliJ.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.spock.example</groupId>
    <artifactId>GroovySpockExample</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>spring_boot</name>
    <description>Demo Example of Groovy with Spock</description>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.spockframework</groupId>
            <artifactId>spock-core</artifactId>
            <version>1.0-groovy-2.4</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>2.4.4</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.18.1</version>
                <configuration>
                    <includes>
                        <include>**/*Test.java</include>
                        <include>**/*Spec.java</include>
                    </includes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

 

  • Create a Groovy Test file under test folder
import spock.lang.Specification
import spock.lang.Unroll

/**
 * Created by Ajay Kumar on 4/7/2017.
 */
class GroovyTest extends Specification {

    def "Testing:- Null is not allowed in Synchronized Hashtable Collection"() {
        given: "Initialize a Hashtable Connection "
        def table = new Hashtable()
        when: " When an element insert into it"
        table.put("One", "One")
        then: "Size is One"
        table.size() == 1
        when: " When insert a null value"
        table.put(null, null)
        then: "NullPointerException thrown"
        thrown(NullPointerException)
    }

    def "Testing:- Only One null value is allowed in Set Collection"() {
        given: "Initialize a HashSet Connection "
        def set = new HashSet()
        when: " When an element insert into it"
        set.add("One")
        and: " And add a Null element into it"
        set.add(null)
        and: "And add another null value"
        set.add(null)
        then: "Size is One"
        set.size() == 2
    }

    def "Testing ArrayList"() {
        given:
        def array = new ArrayList();
        when: "Push an element into Array"
        array.add("Hello")
        then: "One element is expected in Array"
        array.size() == 1
        array.isEmpty() == false
        when: "Pop out element from Array"
        array.remove(0)
        then:
        array.size() == 0
        when: "When we get elements from Array"
        array.get(0)
        then:
        thrown(IndexOutOfBoundsException)
    }

    @Unroll
    def "Power of #val is #result"() {
        expect:
        Math.pow(val, 2) == result
        where:
        val || result
        1   || 1
        2   || 4
        3   || 9
        4   || 16
    }

    @Unroll
    def "Power(#base,#exponent) is #result"() {
        expect:
        Math.pow(base, exponent) == result
        where:
        base | exponent || result
        1    | 2        || 1
        2    | 3        || 8
        3    | 4        || 81
        4    | 5        || 1024
    }

    @Unroll
    def "Power(#base,#exponent) == #result1 and Power(#base,2) == #result2"() {
        expect:
        Math.pow(base, exponent) == result1
        and:
        Math.pow(base, 2) == result2
        where:
        base | exponent || result1 | result2
        1    | 2        || 1 | 1
        2    | 3        || 8 | 4
        3    | 4        || 81 | 9
        4    | 5        || 1024 | 16
    }

    @Unroll
    def "Computing the maximum of (#a,#b) is #c"() {
        expect:
        Math.max(a, b) == c

        where:
        a << [5, 3]
        b << [1, 9]
        c << [5, 9]
    }

    @Unroll
    def " #name should have length #length "() {
        expect:
        name.length() == length
        where:
        name << ["Computing", "Should", "Have", "Name"]
        length << [9, 6, 4, 4]
    }
}

Here is Test output:-

 

Thanks

Advertisements