我写了一个使用Mockito 1.9.5的测试。我有HttpGet和HttpPost HttpClient执行,我正在测试以验证每个响应以输入流的形式返回预期结果。
问题在于使用时
Mockito.when(mockedClient.execute(any(HttpPost.class))).thenReturn(postResponse)
和Mockito.when(mockedClient.execute(any(HttpGet.class))).thenReturn(getResponse)
,其中回复是不同的对象,mockedClient.execute()
始终返回getResponse
。
我写的测试如下:
private InputStream postContent;
private InputStream getContent;
@Mock
private FilesHandler hand;
@Mock
private MockHttpClient client;
private MockHttpEntity postEntity;
private MockHttpEntity getEntity;
private MockHttpResponse postResponse;
private MockHttpResponse getResponse;
private String imgQuery = "someQuery";
private ParametersHandler ph;
private FileHandlerImpl fileHand;
private String indexFolder = "src/test/resources/misc/";
private String indexFile = "index.csv";
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
try {
postContent = new FileInputStream(indexFolder + "testContent.txt");
postEntity = new MockHttpEntity(postContent);
postResponse = new MockHttpResponse(postEntity, new BasicStatusLine(new ProtocolVersion("http", 1, 1), 200, "postReasonPhrase"));
getContent = new FileInputStream(indexFolder + "testContent.txt");
getEntity = new MockHttpEntity(getContent);
getResponse = new MockHttpResponse(getEntity, new BasicStatusLine(new ProtocolVersion("http", 1, 1), 200, "getReasonPhrase"));
ph = new ParametersHandler();
fileHand = new FileHandlerImpl(client, ph, indexFolder, indexFile);
} catch (Exception e) {
failTest(e);
}
}
@Test
public void getFileWhenEverythingJustWorks() {
try {
Mockito.when(client.execute(Mockito.any(HttpPost.class))).thenReturn(postResponse);
Mockito.when(client.execute(Mockito.any(HttpGet.class))).thenReturn(getResponse);
fileHand.getFile(hand, imgQuery, ph, "I");
Mockito.verify(hand).rebuildIndex(Mockito.any(String.class), Mockito.any(Map.class), Mockito.any(Map.class), hand);
} catch (IOException e) {
failTest(e);
}
}
正在测试的方法的缩短版本如下。
public void getFile(FilesHandler fileHandlerFl, String query, ParametersHandler ph, String type) {
JsonFactory factory = new JsonFactory();
HttpPost post = preparePost(query, factory);
CloseableHttpResponse response = client.execute(post);
String uri = "https://someuri.com" + "/File";
HttpGet get = new HttpGet(uri);
setParameters(get);
response.close();
response = client.execute(get);
}
与往常一样,您可以提供任何帮助。
答案 0 :(得分:3)
尽管在Mockito 1.x,any(HttpGet.class)
matches any value and not just any HttpGet中用英语阅读时意味着什么。该参数仅用于保存Java 8之前的强制转换。
来自Matchers.any(Class) documentation:
匹配任何对象,包括空值
此方法不使用给定参数进行类型检查,只是为了避免在代码中进行转换。但是,这可能会在未来的主要版本中发生变化(可以添加类型检查)。
请改为使用isA(HttpGet.class)
和isA(HttpPost.class)
,并参阅下面的Brice评论,了解any(Class<?> clazz)
匹配器的未来更改。