Android测试Handler.postDelayed

时间:2014-07-08 21:42:36

标签: android unit-testing handler robolectric postdelayed

我是Android上的新手并且在测试SplashScreen时遇到困难,基本上我正在做的是尝试测试启动画面持续3秒。这是splashScreen的代码

@Override
protected void onStart() {
    super.onStart();

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            Intent i = new Intent(SplashScreenActivity.this, MainActivity.class);
            startActivity(i);
            finish();
        }
    }, SPLASH_TIME_OUT);
}

这是我的测试方法:

@Test
public void splashScreenTimerTest() throws InterruptedException {
    StopWatch timer = new StopWatch();
    timer.start();

    splashScreenActivityController.start();

    timer.stop();
    long expected = 3000L;
    assertThat(String.format("The spalash screen run for longer than expected. It should stay on for [%d] but it run for [%d]",expected,timer.getTime()),timer.getTime(),equalTo(expected));
}

我正在使用Android + Robolectric进行测试。

我一直在谷歌搜索几天,我尝试了很多东西,但根本没有结果。我尝试获取UI线程并等待它。我试图让你的调度程序获取队列,看看那里是否有任何任务。但根本没有结果。

有任何建议我如何让我的测试等到新活动被触发?

由于

3 个答案:

答案 0 :(得分:25)

Robolectric 3.0 中,他们更新了此API。实际版本:

ShadowLooper.runUiThreadTasksIncludingDelayedTasks();

用法示例:

public class MainActivity extends AppCompatActivity {
    ........

    public void finishGame() {
        Handler h = new Handler();
        h.postDelayed(new Runnable() {
            @Override
            public void run() {
                finish();
            }
        }, 5000);
    }
}

测试它:

@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk=21)
public class MainActivityTest {

    @Test
    public void testFinishing() throws InterruptedException {
        MainActivity mainActivity = new MainActivity();

        assertFalse(mainActivity.isFinishing());

        mainActivity.finishGame();
        ShadowLooper.runUiThreadTasksIncludingDelayedTasks();

        assertTrue(mainActivity.isFinishing());
    }
}

答案 1 :(得分:7)

您可以尝试:

Robolectric.pauseMainLooper();
Robolectric.getUiThreadScheduler().advanceBy(intervalMs);
Robolectric.unPauseMainLooper();

或者,如果你只是被称为runnable:

Robolectric.runUiThreadTasksIncludingDelayedTasks();

答案 2 :(得分:2)

在Robolectric 3.0中,IuriiO的答案将转化为 -

ShadowLooper.pauseMainLooper();
Robolectric.getForegroundThreadScheduler().advanceBy(intervalMs);
ShadowLooper.unPauseMainLooper();