How to use Spock for unit testing
Spock is a testing framework based on Groovy language, which provides rich DSL (Domain-specific language) to write unit tests. Spock can test both Java code and Groovy code, and it is based on JUnit and highly compatible with JUnit. Spock is characterized by its ease of reading, writing, and maintenance.
Below are several key methods commonly used in Spock and corresponding Java sample codes:
1. 'given()': Used to set preset conditions for the testing environment.
given:
def list = new ArrayList<String>()
2. 'when()': Used to call the tested method or trigger the event to be tested.
when:
list.add("item")
3. 'then()': Used to verify whether the test results meet expectations.
then:
list.size() == 1
list.contains("item")
4. 'expectations {}': used to define the expected behavior of a method call.
given:
def calculator = Mock(Calculator)
when:
def result = calculator.add(2, 3)
then:
result == 5
expectations:
1 * calculator.add(2, 3) >> 5
5. 'cleanup()': Used to clean up test data or resources.
cleanup:
//Clean up code
6. '@ SpockTest': Used to mark the test class to enable it to run Spock tests.
@SpockTest
class MyUnitTest { }
Spock uses Maven for dependency management and needs to add the following Maven dependencies to the project's' pom. xml 'file:
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-core</artifactId>
<version>2.0-M2-groovy-2.5</version>
<scope>test</scope>
</dependency>
When writing test classes, you can use the annotations and keywords provided by Spock to write test code. The above are just some common methods and usage in Spock, which provides more features and flexibility to meet different testing needs.