所以我有这个Splash屏幕运行良好,但我想测试"处理程序是否已经启动了下一个活动"。 类:
public class SplashActivity extends Activity {
private final int SPLASH_DISPLAY_LENGTH = 3000;
private TextView quote_text;
private int[] quote_id = {R.string.quote_1, R.string.quote_2, R.string.quote_3, R.string.quote_4, R.string.quote_5};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splashscreen);
quote_text = (TextView) findViewById(R.id.quote_text);
int idx = new Random().nextInt(quote_id.length);
int selectedID = (quote_id[idx]);
quote_text.setText(getResources().getText(selectedID));
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent mainIntent = new Intent(SplashActivity.this, MainActivity.class);
SplashActivity.this.startActivity(mainIntent);
SplashActivity.this.finish();
}
}, SPLASH_DISPLAY_LENGTH);
} }
Robolectric: 测试,这是失败的 assertEquals(expectedIntent,shadowOf(activity).getNextStartedActivity());
@Test
public void testNextActivityWasLaunchedWithIntent() {
SplashActivity activity = Robolectric.buildActivity(SplashActivity.class).create().start().resume().get();
assertNotNull("MainActivity is not instantiated", activity);
synchronized (this)
{
try {
this.wait(3200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Intent expectedIntent = new Intent(activity, MainActivity.class);
assertNotNull(expectedIntent);
assertEquals(expectedIntent,shadowOf(activity).getNextStartedActivity());
}
任何人都可以告诉我,我该怎么测试,处理程序是否解雇了我的下一个活动? 非常感谢你!
答案 0 :(得分:1)
这可以通过一些流行的单元测试框架来检查以启动正确的意图。请参阅下面的Robolectric文档。
Intent expectedIntent = new Intent(activity, WelcomeActivity.class);
assertThat(shadowOf(activity).getNextStartedActivity()).isEqualTo(expectedIntent);
答案 1 :(得分:1)
我可以通过执行以下操作在我的应用中成功测试启动画面:
public void test(){
ActivityController<SplashScreen> controller = Robolectric.buildActivity(SplashScreen.class).create().start();
ShadowLooper.runUiThreadTasksIncludingDelayedTasks();
SplashScreen splashScreenActivity = controller.get();
Intent expectedIntent = new Intent(splashScreenActivity, PrimeiroAcessoActivity.class);
assertEquals(expectedIntent,shadowOf(splashScreenActivity).getNextStartedActivity());}
在我看来,你错过了ShadowLooper.runUiThreadTasksIncludingDelayedTasks()
行。如this StackOverflow post中所述,在Handler.postDelayed中运行代码是必需的。