简体   繁体   中英

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 ?

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);

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