Mockito when () unterscheidet nicht zwischen untergeordneten Klassen
Ich habe einen Test geschrieben, der Mockito 1.9.5 verwendet. Ich habe ein HttpGet und ein HttpPost welches ein HttpClient execute und ich teste, um zu überprüfen, ob die jeweilige Antwort das erwartete Ergebnis in Form eines Eingabestreams zurückgibt.
Das Problem ist, dass bei der Verwendung vonMockito.when(mockedClient.execute(any(HttpPost.class))).thenReturn(postResponse)
undMockito.when(mockedClient.execute(any(HttpGet.class))).thenReturn(getResponse)
, wo die Antworten unterschiedliche Objekte sind,mockedClient.execute()
gibt immer @ zurügetResponse
.
Der Test, den ich geschrieben habe, ist unten:
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);
}
}
Eine verkürzte Version der getesteten Methode finden Sie unten.
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);
}
Wie immer ist jede Hilfe, die Sie leisten können, willkommen.