简体   繁体   English

Spock测试,仅检查方法是否已调用且不执行

[英]Spock Test, only check if method is called and do not execute it

In our Spock tests we want to check if the correct path in our software is selected. 在我们的Spock测试中,我们要检查是否在软件中选择了正确的路径。 But we do not want to test the function of the methods which are called (this is done in separate tests) 但是我们不想测试所调用方法的功能(在单独的测试中完成)

def "Test"() {
    setup:
    service.metaClass.innerMethod = { -> return null }

    when:
    service.doSomething("notexisting@test.com")

    then:
    1 * service.innerMethod(*_)
}

This test always fails, because the code in the innerMethod is called and the invocations of the method calls in the innerMethod are counted and not the invocation of the method innerMethod 这个测试总是失败,因为在代码innerMethod被调用,并在方法调用的调用innerMethod计数,而不是方法的调用innerMethod

|  Too few invocations for:
    1 * service.innerMethod(*_)   (0 invocations)

Unmatched invocations (ordered by similarity):

    1 * secondService.doSomething()

How can I just get the invocation of innerMethod and mock the complete function away? 我怎样才能得到innerMethod的调用并模拟完整的函数呢?

If you are not mocking the service itself, you would need to do something like this (be aware of passing the proper parameters when using metaClass: 如果您不模拟服务本身,则需要执行以下操作(请注意在使用metaClass时传递正确的参数:

def "Test"() {
    setup:
        def calls = 0
        service.metaClass.innerMethod = { p1 -> calls++ }
    when:
        service.doSomething("notexisting@test.com")
    then:
        calls==1
}

and if you are mocking the service, 如果您嘲笑该服务,

def "Test"() {  
    when:
        service.doSomething("notexisting@test.com")
    then:
        1 * service.innerMethod(_)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM