重载方法的Groovy单元测试

时间:2012-11-08 22:09:07

标签: java unit-testing testing groovy mocking

使用Mock如何为重载方法编写单元测试。

例如

public HttpResponse execute(HttpUriRequest request, HttpContext context)

public HttpResponse execute(HttpHost target, HttpRequest request)

我写道:

        def responseMocker = new MockFor(HttpResponse.class)
        HttpResponse response = responseMocker.proxyInstance()
        def requestMocker = new MockFor(HttpUriRequest.class)
        def request = requestMocker.proxyInstance()
        def contextMocker = new MockFor(HttpContext.class)
        def context = contextMocker.proxyInstance();
        def clientMocker = new MockFor(HttpClient.class)
        clientMocker.demand.execute(request, context) { response }

        HttpClientSample client = new HttpClientSample(clientMocker.proxyInstance())

        assertEquals response, client.execute(request,context)

上面的测试失败了:

groovy.lang.MissingMethodException:没有方法签名:....

1 个答案:

答案 0 :(得分:2)

您需要指定所需的方法:

mock.demand.execute { HttpUriRequest request, HttpContext context -> ... }
mock.demand.execute { HttpHost target, HttpRequest request -> ... }

这会将所需方法绑定到适当的重载方法签名。