Reputation: 3285
I am trying to test a set of API's from a Android library. One of such api is a synchronous method which returns immediately after called with the status. But internally that method will create few threads to do some background tasks.
Here when I write a junit test case to test this api, my test case calls the api and then ends the tests. I need to make my testcase to wait for sometime till the thread which is created by that api also completes its tasks.
When tried thread.sleep()
junit pauses the thread, and nothing proceeds.
How do I make my junit testcase to wait until other threads created by the testing method is completed ?
Upvotes: 1
Views: 565
Reputation: 24857
You can test these types of calls by setting a custom background executor. This will cause all threads to be executed on the same thread in order and allow you to use junit to test these actions.
Create a fake executor class like so:
public class FakeExecutor implements Executor {
@Override
public void execute(Runnable runnable) {
runnable.run();
}
}
Set your fake executor in your test either in a before call or just at the start of your test:
BackgroundExecutor.setExecutor(new FakeExecutor());
Upvotes: 1