0

我试图弄清楚如何使用较新的 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();
            }
        });
    }

我收到一个错误,不确定我是否在吠叫正确的树。

java.lang.IllegalStateException: 必须从 android.app.Activity.recreate(Activity.java:4620) 的主线程调用

4

1 回答 1

1

您应该能够使用注释@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();
          }
       });
  }
于 2016-08-08T20:47:18.897 回答