Тест Android Espresso Intents случайно проваливается, `` init () должен быть вызван перед использованием этого метода``
Сейчас я работаю над тем, чтобы подтолкнуть проект к тестированию эспрессо. Я прочитал кучу документов и следую приведенным рекомендациям, чтобы начать.
Все работает нормально, однако, когда дело доходит до теста Intents, результат странный.
Большую часть временитесты пройдены на моем Mac, но не пройдены в Windows моего коллеги (не все тесты не пройдены) с сообщением об ошибкеjava.lang.IllegalStateException: init() must be called prior to using this method
.
Как ни странно, если мы запустим тест отладки в Android Studio, поток кода будет шаг за шагом проходить.
вот тестовый код:
@RunWith(AndroidJUnit4.class)
@LargeTest
public class MainActivityTest {
@Rule public IntentsTestRule<MainActivity> mRule = new IntentsTestRule<>(MainActivity.class, true, false);
AccountManager accountManager;
MainActivity activity;
private void buildLoginStatus() throws AuthenticatorException {
DanteApp app = (DanteApp) InstrumentationRegistry.getTargetContext().getApplicationContext();
accountManager = app.getDanteAppComponent().accountManager();
DoctorModel doctorModel = AccountMocker.mockDoctorModel();
accountManager.save(doctorModel.doctor);
accountManager.setAccessToken(doctorModel.access_token, false);
}
@Before public void before() throws Exception {
buildLoginStatus();
// must login
assertThat(accountManager.hasAuthenticated(), is(true));
activity = mRule.launchActivity(null);
// block all of the outer intents
intending(not(isInternal())).respondWith(new Instrumentation.ActivityResult(Activity.RESULT_OK, null));
}
@After public void tearDown() throws Exception {
accountManager.delete();
}
// failed
@Test public void testViewDisplay() throws Exception {
// check tabhost is displayed
onView(withClassName(equalTo(TabHost.class.getName()))).check(matches(isDisplayed()));
// check toolbar is displayed
onView(withClassName(equalTo(ToolBar.class.getName()))).check(matches(isDisplayed()));
}
// passed
@Test public void testCallServiceHotline() throws Exception {
// switch to the account tab layout
onView(withChild(withText(R.string.account))).perform(click());
// click account menu to make a service call
onView(withId(R.id.contact)).perform(click());
// check call start expectly
intended(allOf(
not(isInternal()),
hasAction(Intent.ACTION_DIAL),
hasData(Uri.parse("tel:" + activity.getString(R.string.call_service)))
));
}
// failed
@Test public void testOpenSettingsUI() throws Exception {
// stub all internal intents
Intents.intending(isInternal())
.respondWith(new Instrumentation.ActivityResult(Activity.RESULT_OK, null));
onView(withChild(withText(R.string.account))).perform(click());
onView(withId(R.id.setting)).perform(click());
// check open settings activity successfully
intended(anyOf(
hasComponent(SettingActivity.class.getName())
));
}
}
Версия библиотеки тестирования (почти все зависимости обновлены, и для тестирования мы используем как физические устройства, так и эмулятор):
правило: 0.4.1бегун: 0.4.1эспрессо- *: 2.2.1support- *: 23.1.0Любая идея заслуживает высокой оценки. Спасибо!