1

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

例如

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:没有方法签名:....

4

1 回答 1

2

您需要像这样指定所需的方法:

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

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

于 2012-11-09T09:34:07.157 回答