Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我们可以在Java中有条件地模拟对象吗?_Java_Unit Testing_Junit_Mockito - Fatal编程技术网

我们可以在Java中有条件地模拟对象吗?

我们可以在Java中有条件地模拟对象吗?,java,unit-testing,junit,mockito,Java,Unit Testing,Junit,Mockito,我使用的是Mockito,我遇到了一个奇怪的情况,我必须对客户端进行身份验证,然后使用相同的代码进行实际的API调用: //@Mock //I want to mock this only for authentication CloseableHttpClient httpClient; //when(httpClient.execute(any(HttpUriRequest.class))).thenReturn(someResponse); response = httpClient

我使用的是Mockito,我遇到了一个奇怪的情况,我必须对客户端进行身份验证,然后使用相同的代码进行实际的API调用:

//@Mock //I want to mock this only for authentication
CloseableHttpClient httpClient;

 //when(httpClient.execute(any(HttpUriRequest.class))).thenReturn(someResponse);

response = httpClient.execute(httpUriRequest);

现在我想使用实际的httpClient对象进行身份验证,并使用模拟的httpClient对象进行实际的API调用。我怎样才能达到这个要求?

谢谢大家的回复

我用
Mockito.spy()解决了这个问题。

如果将来有人觉得我的解决方案有用,就放弃它

    @Test
    public void myTest(){

    //This object will be a normal instance
    CloseableHttpClient httpClient;

    //Authentication: /oauth/token
    //response is real because httpClient is an actual instance.
    response = httpClient.execute(httpUriRequest);

    CloseableHttpClient spyHttpClient = Mockito.spy(httpClient);
    doReturn(mockedCloseableHttpResponse).when(spyHttpClient).execute(any(HttpUriRequest.class));

    //Actual API call: /v1/users
    //response is mockedCloseableHttpResponse because httpClient is a spy instance.
    response = httpClient.execute(httpUriRequest);

    //Assertion code here

    }

以下是有关mockito spy的更多详细信息:

谢谢大家的回复

我用
Mockito.spy()解决了这个问题。

如果将来有人觉得我的解决方案有用,就放弃它

    @Test
    public void myTest(){

    //This object will be a normal instance
    CloseableHttpClient httpClient;

    //Authentication: /oauth/token
    //response is real because httpClient is an actual instance.
    response = httpClient.execute(httpUriRequest);

    CloseableHttpClient spyHttpClient = Mockito.spy(httpClient);
    doReturn(mockedCloseableHttpResponse).when(spyHttpClient).execute(any(HttpUriRequest.class));

    //Actual API call: /v1/users
    //response is mockedCloseableHttpResponse because httpClient is a spy instance.
    response = httpClient.execute(httpUriRequest);

    //Assertion code here

    }

以下是有关mockito spy的更多详细信息:

为什么需要这样做?您是在测试身份验证还是API调用?如果您正在测试身份验证,为什么需要拨打电话?可能是个问题你为什么要这么做?您是在测试身份验证还是API调用?如果您正在测试身份验证,为什么需要拨打电话?可能是一个