Spock is a testing framework written in Groovy but able to test both Java and Groovy code. It is fully compatible with JUnit (it actually builds on top of the JUnit runner).

Spock allows dynamic method names:-

def “maximum of #a and #b is #c”() {


dao.maxNum(a, b) == c
a | b || c
1 | 7 || 7
8 | 4 || 8
9 | 9 || 9
After executing the above code using JUnit, we can see the method names as

Mocking in Spock Framework:

In the following example, we are mocking StudentDao class. We can mock a class in two ways
1. StudentDao studentDao = Mock()
2. def studentDao = Mock(StudentDao)

class StudentServiceSpec extends Specification{
StudentDao studentDao = Mock()
StudentService studentService = new StudentService(studentDao)
def “inserting Student Details”(){
studentDao.insertStudent(_ as Student) >> 1
studentDao.getLastRecordId() >> 70
def response = studentService.insertStudent(new Student())
def se = (Student)response.getEntity()
response != null
se.getStudentId() == 70

      WireMock is great at mocking out HTTP APIs when writing integration tests.

Integration Test using WireMock in Spock Framework:

class StudentRestServiceIT extends Specification {
public WireMockRule server = new WireMockRule(wireMockConfig().port(9000))
IStudentMiddleService studentMiddleService
static String PATH = ‘/vod/accountInfo’
def ‘validate Get Student by accountNumber ‘() {
StudentMiddleMessage studentMiddleMessage = studentMiddleService.getStudent(‘8087300010143918’)
studentMiddleMessage != null
studentMiddleMessage.getStudentSet() != null
studentMiddleMessage.getStudentSet().getCredit() == ‘4779.37’
studentMiddleMessage.getStudentSet().getStudentItems() != null
studentMiddleMessage.getStudentSet().getStudentItems().size() == 1

Why did we chose Spock:

  • Spock has built-in support for Mocking and Stubbing without an external library.
  • One for the killer features of Spock is the detail it gives when a test fails. JUnit only mentions the expected and actual value, where Spock records the surrounding running environment mentioning the intermediate results and allowing the developer to pinpoint the problem with greater ease than JUnit.


In Spock, we don’t have tests, we have specifications. These are normal Groovy classes that extend the Specification class, which is actually a JUnit class. Our class contains a set of specifications, represented by methods with funny-method-names-in-quotes. The funny-method-names-in-quotes take advantage of some Groovy magic to let us express our requirements in a very readable form. And since these classes are derived from JUnit, we can run them from within Eclipse like a normal Groovy unit test.