I'd like to write an integration test to test one asynchronous part of my system as a black box and I'm trying to use mockwebserver for this task.
My problem is that if I don't know how to wait for the callback without blocking the main thread:
As a simplified example of what I need:
Imagine the following interface provided by one class:
public class Checker {
interface Callback {
public void onStatusOK();
public void onStatusFail();
}
void checkStatus(String param, Callback callback){
/* Send HTTP request and call the callback with the result*/
}
}
At some point after calling checkStatus
the app should send an http request to http://ift.tt/2gyisjF
and call to the callback (in the main thread) with onStatusFail()
if the http status code of the request is between 500 and 599, else it should call to onStatusOK()
.
So my test is:
@Test
public void testStatusCallback(){
CountDownLatch countDownLatch= new CountDownLatch(1);
MockWebServer server = new MockWebServer();
// Schedule some responses.
server.enqueue(new MockResponse().setBody("OK").setResponseCode(200));
// Start the server.
server.start();
NetworkingClass.setBaseUrl(server.url("/"));
Callback spyCallback= spy(new Callback() {
public void onStatusOK(){
countDownLatch.countDown();
}
public void onStatusFail(){
countDownLatch.countDown();
}
});
mChecker.checkStatus("test",spyCallback);
countDownLatch.await();
verify(spyCallback).onStatusOk();
server.shutdown();
}
But since the callback is received in the main thread the call to countDownLatch.await(); block it and the tests gets blocked.
How can I solve this?
Aucun commentaire:
Enregistrer un commentaire