如何在 Spock 中模拟方法时验证方法是否被调用

How to verify if method was called when the method is mocked in Spock

我在使用 spock 时遇到一些奇怪的错误。 我模拟了一些方法,它起作用了,而且行为是正确的。但是当我想验证是否调用了mocked方法时,mock根本不起作用

示例代码如下:

import spock.lang.Specification
class MockServiceSpec extends Specification {

    private TestService service = Mock()

    void setup() {
        service.get() >> {
            println "mocked method called" // print some log and it proves that this mock is realy not work in second test
            return "mocked result"
        }
    }

    def "worked perfect"() {
        when:
        String r = service.get()
        then:
        r == "mocked result"
    }
    
    def "verify if get() is called and return null"() {
        when:
        String r = service.get()
        then:
        r == null  // why??
        1 * service.get()
    }

    class TestService {
        public String get() {
            return "real result";
        }
    }
}

两项测试均通过:

您正在重写模拟方法,并且未提供 return 值,因此结果为 null。尝试:

    def "verify if get() is called and returns exactly what it's told to"() {
        when:
        String r = service.get()

        then:
        r == "ok"  // returns exactly what you mock on the next line

        1 * service.get() >> "ok"
    }