在(Espresso)Android仪器测试中启动特定的导体控制器

时间:2017-04-11 05:35:46

标签: java android testing android-espresso conductor

我正在为使用Conductor编写的应用编写Espresso测试。我想指定为每个测试启动哪个控制器,这样我就不需要让Espresso从每个开始的Activity开始点击应用程序。由于只有一个活动而且关于导体的SO或谷歌没有太多,我能找到的最接近的是this问题?或者这不可能吗?

我尝试将路由器设置为静态并添加一个getter,以尝试设置特定的root用于测试但没有成功。

  

android.view.ViewRootImpl $ CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能触及其视图。

在MainActivity中:

public static Router getRouter() {
    return router;
}

在仪器测试中:

@Rule
public ActivityTestRule<MainActivity> testRule = new ActivityTestRule<>(MainActivity.class);

@Before
public void setUp() {
    Router router = testRule.getActivity().getRouter();
    router.setRoot(RouterTransaction.with(new ControllerIwantToTest()));
}

@Test
public void titleIsDisplayed() {
    onView(withText("My Controllers Title")).check(matches(isDisplayed()));
}

1 个答案:

答案 0 :(得分:5)

如果有其他人遇到同样的问题,我通过执行以下操作解决了问题:

@RunWith(AndroidJUnit4.class)
public class NoBundleControllerEspressoTest {

private Router router;

@Rule
public ActivityTestRule<NoBundleConductorActivity> testRule = new ActivityTestRule<>(NoBundleConductorActivity.class);

@Before
public void setUp() {
    Activity activity = testRule.getActivity();
    activity.runOnUiThread(() -> {
               router = testRule.getActivity().getRouter();
               router.setRoot(RouterTransaction.with(new NoBundleController()));
           });
}

@Test
public void titleIsDisplayed() {
    onView(withText("Super Awesome Title")).check(matches(isDisplayed()));
    }
}

或者,如果您的控制器在我们的大部分时间内使用Bundle构造函数:

@RunWith(AndroidJUnit4.class)
public class BundleControllerEspressoTest {

private Router router;
private ControllerBundleData controllerData;

@Rule
public ActivityTestRule<BundleConductorActivity> testRule = new ActivityTestRule<>(BundleConductorActivity.class);

@Before
public void setUp() {
    controllerData = new ControllerBundleData();
    Bundle bundle = new Bundle();
    bundle.putSerializable(YOUR_BUNDLE_KEY, controllerData);

    Activity activity = testRule.getActivity();
    activity.runOnUiThread(() -> {
               router = testRule.getActivity().getRouter();
               router.setRoot(RouterTransaction.with(new BundleController(bundle)));
           });
}

@Test
public void titleIsDisplayed() {
    onView(withText("Super Awesome Title")).check(matches(isDisplayed()));
    }
}