5

我正在为使用Conductor编写的应用程序编写 Espresso 测试。我想为每个测试指定要启动哪个控制器,这样我就不需要让 Espresso 从每个测试的开头 Activity 中单击应用程序。由于只有一个 Activity 并且在 SO 或 google 上没有太多关于 Conductor 的内容,所以我能找到的最接近的是这个问题?或者这是不可能的?

我尝试将路由器设置为静态并添加一个吸气剂以尝试设置特定的根以进行测试,但没有成功。

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

1 回答 1

8

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

@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()));
    }
}
于 2017-04-11T06:31:26.577 回答