vendredi 9 septembre 2016

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 ?

Aucun commentaire:

Enregistrer un commentaire