Android测试Handler.postDelayed [英] Android Testing Handler.postDelayed
问题描述
我是Android上的新手,并且被困在测试SplashScreen上,基本上我正在做的是尝试测试启动画面是否保持3秒钟.这是splashScreen的代码
I'm newbie on Android and get stuck on testing a SplashScreen, basically what I'm doing is trying to test that the splash screen stays on for 3s. this is the code for the 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进行测试.
I'm using Android+Robolectric for testing.
我已经谷歌搜索了几天,我尝试了很多事情,但完全没有结果.我尝试获取UI线程并等待它.我试图向您的调度程序获取队列,看看那里是否有任何任务.但根本没有结果.
I've been googling for a couple days, I tried many things but no result at all. I try to get the UI Thread and wait for it. I tried to you scheduler to get the queue and see if there is any task there. But no result at all.
有什么建议可以让我的测试等待新的活动被触发吗?
Any suggestion how can I make my test wait until the new Activity is triggered?
谢谢
推荐答案
在 Robolectric 3.0 中,他们更新了此API.实际版本:
In Robolectric 3.0, they updated this API. The actual version:
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());
}
}
这篇关于Android测试Handler.postDelayed的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!