简体   繁体   中英

How to test AsyncTask using Robolectric?

I use Android-DDP library in my application. This library implements the Distributed Data Protocol .

I would like to implement some integration tests, in which I don't want to mock the DDP-client . I've setup the backend instance on the same machine, so I don't worry about network issues.

I started with such test structure:

@Inject
Meteor meteor;

@Test
public void testSendMessage() throws Exception {
    final Object[] params = new Object[]{"example params"};//some params are build here.

    final Result result = Result.empty(); //my class for tests;
    final CountDownLatch latch = new CountDownLatch(1);
    meteor.call("send_message", params, new ResultListener() {
        @Override
        public void onSuccess(String result) {
            result.setSucess(result);
            latch.countDown();
        }

        @Override
        public void onError(String error, String reason, String details) {
            result.setError(error, reason, details);
            latch.countDown();
        }
    });
    latch.await(); // here we block the main thread, and callback will not be called because of it.

    //here goes some assertions, but they will never call.
}

But the callback was never called. After a small investigation, I've found that under the hood, ddp-client uses AsyncTask to perform background operation and to deliver callbacks to the client code.

Since AsyncTask.onPostExecute is always called on the main thread I am not able to get call from callback: Tests blocks the main thread until the callback is called, but callback is never called because AsyncTask.onPostExecute is called on the main thread (which is blocked by tests)

So, to solve the problem I need to run tests or AsyncTask.onPostExecute in different threads, or somehow not to block the thread to test the result. Is that possible to do?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM