如何在控制器单元测试中模拟Grails 4服务 [英] How can I mock a grails 4 service in a controller unit test

查看:91
本文介绍了如何在控制器单元测试中模拟Grails 4服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白在Grails 4.0中模拟是如何工作的. 我有一个失败的单元测试(这只是真实测试的说明,真实测试实际上涉及控制器):

I don't understand how mocking works in Grails 4.0. I have this unit test that fails (it is just an illustration of the real test, the real test actually involves the controller):

import com.myapp.MySearchService

class ApiControllerSpec extends Specification implements ControllerUnitTest<ApiController> {

    def setup() {
    }

    def cleanup() {
    }

    void "test listSources"() {
        given:
        def mock = Mock(MySearchService) {
            find(_) >> [["label": "abc", "description": "xsad"]]
        }

        when:
        System.out.println(mock.find(''))

        then:
        1 * mock.find(_) >> [["label": "abc", "description": "xsad"]]
    }

有错误

Too few invocations for:

1 * mock.find(_) >> [["label": "abc", "description": "xsad"]]   (0 invocations)

Unmatched invocations (ordered by similarity):

1 * mock.invokeMethod('find', [<java.lang.String@0 value= hash=0>])


    at org.spockframework.mock.runtime.InteractionScope.verifyInteractions(InteractionScope.java:93)
    at org.spockframework.mock.runtime.MockController.leaveScope(MockController.java:77)
    at toe.ApiControllerSpec.test listSources(ApiControllerSpec.groovy:29)

和标准输出

null

有趣的是,如果我使用非常简单的测试类而不是MySearchService ,则可以很好地工作.因此,我假设它必须与Grails/Spring的设置方式有关.这也可能解释了以下几行:

The interesting thing is that this works fine if I use a very simple test class instead of MySearchService. So I am assuming that it has to do something with the way Grails/Spring is setup. This might also explain the lines:

Unmatched invocations (ordered by similarity):

1 * mock.invokeMethod('find', [<java.lang.String@0 value= hash=0>])

但是我该如何设置它呢?我在文档的任何地方都找不到.感谢您的帮助!

But how do I set it up otherwise? I can't find this anywhere in the documentation. Thanks for any help!

相似的问题(无答案): 如何在Grails集成测试中部分模拟服务

Similar question (without answer): How to partially mock service in Grails integration test

推荐答案

模拟的语法不正确-这是在Grails 4.0.1中测试的有效示例

The syntax for your mock is incorrect - here's a working example tested in Grails 4.0.1

    void "test something"() {
        given:
        def mock = Mock(SearchService) {
            1 * find(_) >> ['foobar'] // note the interaction count is required when defining this way.
        }

        when:
        def result = mock.find('')

        then:
        result == ['foobar']
    }

请参阅- http://spockframework.org/spock/docs/1.0/interaction_based_testing .html -部分:Declaring Interactions at Mock Creation Time

请注意,Grails文档中可能没有此内容,因为没有任何Grails特定信息,只有Spock.

Note this is likely not in the Grails docs as there is nothing Grails specific about it - just Spock.

这篇关于如何在控制器单元测试中模拟Grails 4服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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