我正在为使用 Conductor 编写的应用编写 Espresso 测试.我想为每个测试指定启动哪个 Controller ,这样我就不需要让 Espresso 从每个测试的开始 Activity 开始点击应用程序。由于只有一个 Activity ,SO 或谷歌上关于 Conductor 的信息不多,我能找到的最接近的是 this题?或者这是不可能的?
我试过使路由器静态并添加一个 getter 以尝试设置特定的根以进行测试但没有成功。
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
在主 Activity 中:
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()));
}
最佳答案
如果其他人遇到同样的问题,我已经通过执行以下操作解决了问题:
@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()));
}
}
或者,如果您的 Controller 像我们大多数人一样在其构造函数中使用 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()));
}
}
关于java - 在(Espresso)Android 仪器测试中启动特定的导体 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43337497/