Fork me on GitHub

Using the Spock based on JUnit5 engine

Sample project with Spock/Groovy and JUnit5

This sample code shows you how the Surefire plugin works with Spock/Groovy and JUnit5. The project contains two dependencies spock-core and junit-jupiter-engine, and Groovy compiler gmavenplus-plugin.

You can create tests in test source directory for Groovy (i.e., src/test/groovy). This is an example with parameterized test which is executed twice.

import pkg.Calculator
import spock.lang.Specification

class CalculatorTest extends Specification
{
    def "Multiply: #a * #b = #expectedResult"()
    {
        given: "Calculator"
        def calc = new Calculator()

        when: "multiply"
        def result = calc.multiply( a, b )

        then: "result is as expected"
        result == expectedResult
        println "result = ${result}"

        where:
        a  | b | expectedResult
        1  | 2 | 3
        -5 | 2 | -3
    }
}

If you want to additionally mix Spock tests with the JUnit4, you should add the JUnit Vintage Engine in the test dependencies.

<dependencies>
    [...]
    <dependency>
        <groupId>org.spockframework</groupId>
        <artifactId>spock-core</artifactId>
        <version>2.0-M2-groovy-3.0</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>5.9.1</version>
        <scope>test</scope>
    </dependency>
    [...]
</dependencies>
...
<build>
    <plugins>
        [...]
        <plugin>
            <groupId>org.codehaus.gmavenplus</groupId>
            <artifactId>gmavenplus-plugin</artifactId>
            <version>1.9.0</version>
            <executions>
                <execution>
                    <goals>
                        <goal>compileTests</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.5.0</version>
        </plugin>
        [...]
    </plugins>
</build>
...