1

I want to do Unit Tests for asynchronous methods in android. The result needs to be a "notified by observer's callback". Have a look at the below example. How can I write a unit test case for doSomething() method?

public interface IFooObserver {
    void onResult(String result);
}

public class Foo {

    private IFooObserver mObserver;

    public Foo(IFooObserver observer) {
        mObserver = observer;
    }

    public void doSomething() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // do something..
                mObserver.onResult("hello, world!");
            }
        }).start();
    }
}
Hash
  • 4,647
  • 5
  • 21
  • 39
sunjinbo
  • 2,137
  • 4
  • 22
  • 45
  • 1
    Possible duplicate http://stackoverflow.com/questions/2321829/android-asynctask-testing-with-android-test-framework – Long Ranger Aug 22 '16 at 06:36

1 Answers1

0

Simply: don't use "bare metal" threads.

Use ExecutorServices instead - because that allows you to use dependency injection to turn your multi-threaded code into a single-threaded thing for testing - using a Same Thread Executor Service.

Example:

class Whatever {
   private final ExecutorService service;
   Whatever() { this ( Executors.newSingleThreadExecutor() ); }

   Whatever(ExecutorService service) { this.service = service; }

   void foo() {
     service.submit ( ... whatever

The point is: when you are using a thread directly, you have no control whatsoever there. Most likely, that will lead to test cases that need complicated signaling, or worse: rely on calling sleep() here or there. And that is always bad - it increases the execution time of your tests; or, worse, you get the timing wrong; and occasionally your tests fail during regression. Because of different load on your test system; and threads showing different runtime characteristics.

So, long story short: if possible, avoid using threads directly; instead use the aforementioned concept to simply avoid multiple threads for testing.

Community
  • 1
  • 1
GhostCat
  • 137,827
  • 25
  • 176
  • 248