Spock测试,仅检查方法是否已调用且不执行 [英] Spock Test, only check if method is called and do not execute it

查看:337
本文介绍了Spock测试,仅检查方法是否已调用且不执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的Spock测试中,我们要检查是否在我们的软件中选择了正确的路径.但是我们不想测试被调用方法的功能(这是在单独的测试中完成的)

In our Spock tests we want to check if the correct path in our software is selected. 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(*_)
}

此测试始终失败,因为调用了innerMethod中的代码并且计算了innerMethod中方法调用的调用,而不是方法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

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

Unmatched invocations (ordered by similarity):

    1 * secondService.doSomething()

我怎样才能得到innerMethod的调用并模拟完整的函数呢?

How can I just get the invocation of innerMethod and mock the complete function away?

推荐答案

如果您不模拟服务本身,则需要执行以下操作(请注意在使用metaClass时传递正确的参数:

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:

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

如果您要嘲笑该服务,

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

这篇关于Spock测试,仅检查方法是否已调用且不执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆