【发布时间】:2016-10-12 08:00:00
【问题描述】:
我有一个 Android 应用,它具有继承自 Application 的 MyApplication 类。
我创建了几个使用@RunWith(AndroidJUnit4.class) 运行的单元测试。如果我分别运行每个测试,它们都会通过。如果我一起运行它们 - 第一个通过,然后(其中一些)其他失败。
问题在于,似乎只创建了一个 MyApplication 实例,然后将其保留并用于导致失败的所有测试,因为 MyApplication 中有一个状态必须只初始化一次.
有没有办法运行单元测试 (androidTest),以便为每个测试重新启动应用程序?我不在乎它是否会很慢(例如,每次都必须重新安装应用程序)我只想让测试彼此独立运行。
单元测试的实际代码如下所示(根据@Zinc 的要求):
@RunWith(AndroidJUnit4.class)
public class AutoLogin_ActMainTest {
@Rule
public ActivityTestRule<ActMain> mActivityRule = new ActivityTestRule<ActMain>(
ActMain.class) {
@Override
protected void beforeActivityLaunched() {
super.beforeActivityLaunched();
MyTestApp app = (MyTestApp) InstrumentationRegistry.getInstrumentation().getTargetContext().getApplicationContext();
DependencyInjector.reset();
app.reset();
FakeUnitDaggerModule fudm = new FakeUnitDaggerModule();
Session session = new SessionImpl(new TimeProviderImpl());
fudm.setResMain(new ResMainTest(session));
FakeAppPrefs appPrefs = new FakeAppPrefs();
FakeLoginPrefs loginPrefs = new FakeLoginPrefs();
CurrentUserHolder currentUserHolder = new CurrentUserHolder();
FakeComponent inj = DaggerFakeComponent.builder().
fakeMyAppDaggerModule(new FakeMyAppDaggerModule(app, appPrefs, loginPrefs, currentUserHolder)).
appInfoDaggerModule(new AppInfoDaggerModule("1")).
fakeSessionDaggerModule(new FakeSessionDaggerModule(session)).
fakeExchangeDaggerModule(new FakeExchangeDaggerModule("https://test.com")).
fakeUnitDaggerModule(fudm).
build();
DependencyInjector.init(inj);
DependencyInjector.getInstance().inject(app);
app.onStart();
}
};
@Test
public void testAutoLogin() {
ElapsedTimeIdlingResource idlingResource = new ElapsedTimeIdlingResource(500);
Espresso.registerIdlingResources(idlingResource);
idlingResource.startWaiting();
onView(ViewMatchers.withId(R.id.tv_logged_in_as)).check(matches(isDisplayed()));
Espresso.unregisterIdlingResources(idlingResource);
}
}
【问题讨论】:
-
你能分享你的代码吗?
-
@Zinc 添加了其中一项测试的代码
-
你为什么不使用 degger ?
-
@Saveen degger?什么意思?
-
@Ognyan dagger 用于依赖注入从这里查看square.github.io/dagger
标签: android unit-testing