Spock是用Groovy语言实现的测试框架,可以测试Groovy代码和Java代码。

比JUnit简洁,

class Math extends Specification {
    def "maximum of two numbers"(int a, int b, int c) {
        expect:
        Math.max(a, b) == c

        where:
        a | b | c
        1 | 3 | 3   //passes
        7 | 4 | 4   //fails
        0 | 0 | 0   //passes
    }
}

原生地支持Mocking和Stubbing,不再依赖Mockito之类的mock框架,

def "should send messages to all subscribers"() {
    when:
    publisher.send("hello")

    then:
    1 * subscriber.receive("hello") //subsriber should call receive with "hello" once.
    1 * subscriber2.receive("hello")
}
subscriber.receive(_) >>> ["ok", "error", "error", "ok"]

支持BDD(Behavioral Driven Development),

given: //data initialization goes here (includes creating mocks)
when: //invoke your test subject here and assign it to a variable
then: //assert data here
cleanup: //optional
where: //optional:provide parametrized data (tables or pipes) 

更好的错误提示,

maximum of two numbers   FAILED

Condition not satisfied:

Math.max(a, b) == c
	|    |  |  |  |
	|    7  0  |  7
	42         false

Spock使用了JUnit的runner infrastructure,所以也支持code coverage等报告。

其它参考:

An introduction to Spock
So Why is Spock Such a Big Deal?
Comparing Spock and Junit