Piotr Śmietana
Piotr Śmietana

Reputation: 463

robolectric unit test android Timer

I'm writing unit tests for Android app, which code I shouldn't change. I've encountered a problem with testing a piece of code using java.util.Timer. I'm looking for a way to cause the task to execute immediately, without the need to wait till scheduled time. Because it's created as a local object, I can't mock it with Mockito.

public void testedMethod() {
    long time = 9999;
    final Timer timer = new Timer()

    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            //do stuff
        }
    }, time);
}

@Test
public void test() throws Exception {
    testedObject.testedMethod();

    Thread.sleep(10000);

    //verify that stuff was done
}

I'm using Robolectric (3.1), so I've tried using methods of ShadowLooper and Robolectric classes, but to no avail. Currently I have to use Thread.sleep(), but it's rather unconvienient.

Is there a way to force Timer to execute scheduled TimerTasks, like using ShadowLooper.runToEndOfTasks() to execute Runnables scheduled by Handler ?

Upvotes: 2

Views: 1958

Answers (1)

nenick
nenick

Reputation: 7438

To start your task immediately like the Handler class you could create your own ShadowTimer class to support this behaviour. ShadowLooper only works with handler tasks not with timer tasks.

Here is an basic explanation how to create your own ShadowTimer class http://robolectric.org/extending/

When you may change the existing code then use Android handler mechanism instead of shadowing the timer class. And all what you need exists out of the box.

Handler handler = new Handler();
handler.postDelayed(runnable, 100);

Upvotes: 1

Related Questions