java - Mockito doReturn/when 执行真实方法(没有 CGILIB)

标签 java mocking testng mockito stubbing

我已经做了很多 Mockito spy ,只是在一个新项目中模仿我自己的工作示例。但这惨遭失败

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import static org.mockito.Mockito.*;

public class SpyTest {
    HttpClient httpClient;
    private HttpResponse httpResponse;
    private StatusLine responseStatus;
    private HttpEntity responseEntity;

    @BeforeMethod
    public void setupClient() throws Exception {
        List spy = spy(new ArrayList());
        doReturn(true).when(spy).addAll(any(Collection.class)); // this works!

        DefaultHttpClient directClient = new DefaultHttpClient();
        httpClient = spy(directClient);
        httpResponse = mock(HttpResponse.class);
        responseStatus = mock(StatusLine.class);
        responseEntity = mock(HttpEntity.class);
        doReturn(responseStatus).when(httpResponse).getStatusLine();
        doReturn(responseEntity).when(httpResponse).getEntity();
        doReturn(httpResponse).when(httpClient).execute(any(HttpPost.class)); // failing here
    }

    @Test
    public void itShouldSetupTheSpy() throws Exception {
        doReturn(200).when(responseStatus).getStatusCode();
        doReturn("OK").when(responseStatus).getReasonPhrase();
        doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                OutputStream os = (OutputStream) invocation.getArguments()[0];
                os.write("{\"id\": 100}".getBytes());
                return null;
            }
        }).when(responseEntity).writeTo(any(OutputStream.class));
    }
}

但是我遇到了错误

    java.lang.IllegalArgumentException: Request must not be null.
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:801)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:784)
    at SpyTest.setupClient(SpyTest.java:37)

我相信我已经关注了the official advice !密切关注,就像我的其他 spy 一样。和this answer !似乎不适用于我,因为我不使用 CGLIB,从 Maven 依赖关系树可以明显看出:


    [INFO] +- org.codehaus.jackson:jackson-mapper-asl:jar:1.9.3:compile
    [INFO] |  \- org.codehaus.jackson:jackson-core-asl:jar:1.9.3:compile
    [INFO] +- org.testng:testng:jar:6.8:test
    [INFO] |  +- junit:junit:jar:4.10:test
    [INFO] |  |  \- org.hamcrest:hamcrest-core:jar:1.1:test
    [INFO] |  +- org.beanshell:bsh:jar:2.0b4:test
    [INFO] |  +- com.beust:jcommander:jar:1.27:test
    [INFO] |  \- org.yaml:snakeyaml:jar:1.6:test
    [INFO] +- org.mockito:mockito-all:jar:1.9.5:test
    [INFO] +- com.newrelic:newrelic-api:jar:2.3.0:compile
    [INFO] +- org.apache.httpcomponents:httpclient:jar:4.2.5:compile
    [INFO] |  +- org.apache.httpcomponents:httpcore:jar:4.2.4:compile
    [INFO] |  +- commons-logging:commons-logging:jar:1.1.1:compile
    [INFO] |  \- commons-codec:commons-codec:jar:1.6:compile
    [INFO] \- org.apache.commons:commons-lang3:jar:3.1:compile

看起来 HttpClient 及其子类有问题。

最佳答案

执行final method ,并且 Mockito 无法模拟 final方法(如 the section on spyingthe FAQ 中提到的)。

为什么?因为在正常情况下你不能重写final方法,所以Java采取了一种快捷方式,将调用(对final方法)直接编译到实现中,而不是在Java's equivalent of a virtual method table中查找它们。 。这意味着 Mockito 永远不会参与 final方法调用,因此无法拦截行为,甚至无法接收 stub /验证调用。

你可以切换到模拟并使用 a raw HttpClient反而?您可以模拟接口(interface)的任何方法,而不必担心可见性或 final方法问题。

关于java - Mockito doReturn/when 执行真实方法(没有 CGILIB),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20528472/

相关文章:

java - 如何在范围报告中捕获所有测试用例?

java - 按字母顺序对其中包含数字的字符串进行排序

javascript - 如何在 Jest 中监视 window.scrollTo?

.net - 模拟对象 - 将所有方法声明为虚拟方法还是使用接口(interface)?

java - 使用java自动化实时数据

java - 如何使用 Eclipse 并行运行 TestNG 测试?

java - 这段 Java 代码中构造函数的顺序是什么?

java - 如何编写elasticsearch DSL查询的java代码

java - 模拟 Spring 安全类

.net - "Typemock Isolator"如何模拟静态方法?