Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring 如何在控制器单元测试中模拟Grails4服务_Spring_Unit Testing_Grails_Groovy_Mocking - Fatal编程技术网

Spring 如何在控制器单元测试中模拟Grails4服务

Spring 如何在控制器单元测试中模拟Grails4服务,spring,unit-testing,grails,groovy,mocking,Spring,Unit Testing,Grails,Groovy,Mocking,我不明白模仿在Grails4.0中是如何工作的。 我有一个失败的单元测试(它只是真实测试的一个例子,真实测试实际上涉及控制器): 有趣的是,如果我使用一个非常简单的测试类,而不是MySearchService,那么这一切都很好。因此,我假设它必须与Grails/Spring的设置方式有关。这也可能解释了其中的含义: Unmatched invocations (ordered by similarity): 1 * mock.invokeMethod('find', [<java.lan

我不明白模仿在Grails4.0中是如何工作的。 我有一个失败的单元测试(它只是真实测试的一个例子,真实测试实际上涉及控制器):


有趣的是,如果我使用一个非常简单的测试类,而不是MySearchService,那么这一切都很好。因此,我假设它必须与Grails/Spring的设置方式有关。这也可能解释了其中的含义:

Unmatched invocations (ordered by similarity):

1 * mock.invokeMethod('find', [<java.lang.String@0 value= hash=0>])
不匹配的调用(按相似性排序):
1*mock.invokeMethod('find',[]))
但是我如何设置它呢?我在文档中找不到这个。谢谢你的帮助

类似问题(无答案):

这里已经有一个不太好的解决方法:

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

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

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

模拟的语法不正确-下面是一个在Grails4.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']
    }
请参阅--部分:
在模拟创建时声明交互


请注意,这可能不在Grails文档中,因为Grails没有任何特定于它的内容—只有Spock。

“因此我假设它必须与Grails/Spring的设置方式有关。”—我认为情况并非如此。我不认为Spring是相关的,Grails也是。请参阅下面Eric的答案,其中澄清了发生的情况。
Unmatched invocations (ordered by similarity):

1 * mock.invokeMethod('find', [<java.lang.String@0 value= hash=0>])
    void "test listSources"() {
        given:
        def mock = Mock(MySearchService) {
            invokeMethod('find', _) >> [["label": "abc", "description": "xsad"]]
        }

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

        then:
        1 * mock.invokeMethod('find', _) >> [["label": "abc", "description": "xsad"]]
    }
    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']
    }