Spring 如何在控制器单元测试中模拟Grails4服务
我不明白模仿在Grails4.0中是如何工作的。 我有一个失败的单元测试(它只是真实测试的一个例子,真实测试实际上涉及控制器):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
有趣的是,如果我使用一个非常简单的测试类,而不是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']
}