我们可以在Java中有条件地模拟对象吗?
我使用的是Mockito,我遇到了一个奇怪的情况,我必须对客户端进行身份验证,然后使用相同的代码进行实际的API调用:我们可以在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
//@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调用?如果您正在测试身份验证,为什么需要拨打电话?可能是一个