Trying to unit test a Retrofit 2.0
response using MockWebServer
. I have the webserver setup, but the problem occurs when i am trying to pass a mock json
file as a response. To illustrate, my folder structure is:
src->test->java->package_name->class_name.java
src->test->resources->list_success.json
My unit test:
@Before
public void setUp() throws Exception{
MockitoAnnotations.initMocks(this);
server = new MockWebServer();
serviceHelper = new ServiceHelper();
}
@Test
public void testEventBusIdPostedOnSuccessfulServiceCall() throws Exception {
server.start();
server.enqueue(new MockResponse().setResponseCode(200).setBody(getStringFromFile(RuntimeEnvironment.application, "list_success.json")));
MainActivity.URL = server.url("/").toString();
serviceHelper.getIndividualData("Store","7");
verify(eventBus).post(any());
}
@After
public void tearDown() throws Exception{
server.shutdown();
}
Everything works fine. The retrofit call which is async is triggered with the mock JSON. However, the callback never gets triggered. I tried putting in a countdown latch within the actual service implementation, but nothing happens either.
public void getIndividualData(String item, String number) {
Call<DataList> dataList = RestClient.get().getList(item, number);
dataList.enqueue(new Callback<DataList>() {
@Override
public void onResponse(Response<DataList> response, Retrofit retrofit) {
/*data persistence should take place before sending out the eventbus message.
Passing the response object directly for sample purpose. */
EventBus.getDefault().post(new IndividualItemEvent(response.body().Values));
// latch.countDown(); ---->might be needed for retrofit async unit testing
}
@Override
public void onFailure(Throwable t) {
Log.d("%%%%%", "retrofit failure");
// latch.countDown(); ---->might be needed for retrofit async unit testing
}
});
// try {
// latch.await();
// } catch (InterruptedException e) { ---->might be needed for retrofit async unit testing
// e.printStackTrace();
// }
Am i missing something here? Thanks.