java - 在(Espresso)Android 仪器测试中启动特定的导体 Controller

标签 java android testing android-espresso conductor

我正在为使用 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/

相关文章:

android - 应用程序在每次重启时都会导致 AOT(优化应用程序)

android - 如何在 android dev 的静态 webview 窗口中引用本地 css 文件?

java - Swing Worker 和普通线程之间的区别?

java - 如何实现像Hibernate一样的惰性getObject方法?

java.sql.SQLException : Exhausted Resultset

Ruby:模拟本地对象来测试模块方法

ruby-on-rails - 测试 Rails 应用程序的 Braintree 透明重定向

java - java.util.regex.Matcher::useAnchoringBounds 如何工作?

java - 生成 keystore 时遇到问题 (Java)

validation - 为什么添加 dropout 层对验证集有效,但对测试集无效?