我正试图找出如何使用较新的AndroidJunit4和活动规则测试onSavedInstance。
@RunWith(AndroidJUnit4.class)
public class MyViewActivityTest{
@Rule
public UiThreadTestRule uiThreadTestRule = new UiThreadTestRule();
@Rule
public ActivityTestRule<MyViewActivity> mActivityRule = new ActivityTestRule<>(MyViewActivity.class);
@UiThreadTest
@Test
public void testOnSavedIntanceState() {
uiThreadTestRule.runOnUiThread(new Runnable() {
@Override
public void run() {
Intent in = new Intent();
MyViewActivity activity = mActivityRule.launchActivity(in);
activity.finish();
activity.recreate();
}
});
}
我得到一个错误,不确定我是否在正确的树。
. lang。IllegalStateException:必须从主线程调用android.app.Activity.recreate (Activity.java: 4620)
您应该能够使用注释@UiThreadTest运行测试。它适用于扩展UiThreadTestRule
的每个测试规则。在这种情况下,ActivityTestRule
恰好做到了这一点。
@UiThreadTest
@Test
public void testOnUIThread() {
// Test to run on UI thread
}
编辑:我只是再次运行它,并记得你不能在UI线程上启动活动。我做了这个,并运行它没有任何并发症。
@RunWith(AndroidJUnit4.class)
public class TestActivity {
@Rule
public ActivityTestRule<MyViewActivity> activityRule = new ActivityTestRule<>(MyViewActivity.class, true, false);
@Test
public void testOnSavedInstanceState() throws Throwable {
activityRule.launchActivity(new Intent());
final Activity activity = activityRule.getActivity();
activityRule.runOnUiThread(new Runnable() {
@Override
public void run() {
activity.finish();
activity.recreate();
}
});
}