编程语言
首页 > 编程语言> > java – 在(Espresso)Android仪器测试中启动特定的导体控制器

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

作者:互联网

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

我已经尝试使路由器静态并添加一个getter,试图设置一个特定的root用于测试但没有成功.

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

在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()));
}

解决方法:

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

@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()));
    }
}

标签:java,android,testing,android-espresso,conductor
来源: https://codeday.me/bug/20190622/1265463.html