Mock在spock framewrok中给出了缺少的方法异常

时间:2017-12-08 10:17:07

标签: unit-testing groovy spock

我正在使用spock框架为我的groovy类运行我的Junit测试用例我使用Mock来调用我的类。但是它给了我MissingMethodException但是如果我通过正常的创建对象def obj = new MyClass()方式调用相同的方法它是有效的。请让我知道我错过了什么?下面是我的stacktrace

Expected no exception to be thrown, but got 'groovy.lang.MissingMethodException'
    at spock.lang.Specification.noExceptionThrown(Specification.java:119)
    at .AsplTest.fetchXmlTest(AsplTest.groovy:35)
Caused by: groovy.lang.MissingMethodException: No signature of method: com.webservice.Service.fetchAsplXml() is applicable for argument types: (java.lang.String, groovy.net.xmlrpc.XMLRPCServerProxy, java.lang.String) values: [3c98fa0dd1b5d92af599779bfb7be655, groovy.net.xmlrpc.XMLRPCServerProxy@797b0699, ...]
Possible solutions: getFetchAsplXml()
    at .AsplTest.fetchXmlTest(AsplTest.groovy:33)

下面是我的测试代码

public void fetchXmlTest() {
        given:
        def asplObject=Mock(Service);
        when:
        asplObject.fetchXml(sessionId, serverProxy, "https://serverproxy")
        then:
        noExceptionThrown()
    }

供参考: 我的groovy版本是2.4.12和spock版本1.1-groovy-2.4

1 个答案:

答案 0 :(得分:0)

在我看来,你正在倒退。

模拟不是测试科目。它们用于控制测试对象与其他对象的交互。从您发布的代码中可以看出,您希望在Service对象上测试方法fetchXml的调用。

为此,您需要创建一个Service实例,并调用该方法。如果您的服务具有协作对象,那么您可以模拟它们,并添加交互,如下所示:

given:
def service = new Service()

and:
service.collaboratingObject = Mock(CollaboratingObjectClass)


when:
service.getFetchAsplXml()

then:
1 * service.collaboratingObject.someMethodReturningAString(_ as String) >> {String input-> "mockedResult from $input" as String }
相关问题