根据this link,我可以创建一个测试应用程序,Robolectric将自动开始在测试中使用。我不能让这个工作。
我正在使用Dagger进行依赖注入,并为Activity
和Application
创建了注入包装类。然后我的每个活动都扩展了包装器活动类而不是普通的旧Activity
。
我遇到的问题是,在测试中,Application
模块提供的依赖关系无法解析,因此测试失败。这是因为我们的大多数测试只是构建一个活动(使用Robolectric.buildActivity()
)并且不是从Application
运行。
我希望以某种方式修改Robolectric testrunner以在Application
下运行我们的测试。或者使用上面链接中概述的测试应用程序。
我已经创建了一个测试应用程序,但仍然遇到相同的测试错误,因为测试未在此测试应用程序下运行。我已经尝试将测试应用程序移动到不同的包等,但没有任何改变。
我正在寻找一些关于如何去做我想要的建议。对那些有Dagger经验以及他们如何进行测试的人特别感兴趣。
在Robolectric 3.0中它非常简单,你可以直接将其添加到@Config
注释中。
@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21,application = TestApplication.class)
public class ActivityTest {
道歉,忘记了这一点。为了解决这个问题,我在测试中创建了一个TestApplication
。然后我修改了我们的TestRunner
(扩展RobolectricTestRunner
)到:
public class TestRunner extends RobolectricTestRunner {
public TestRunner(final Class<?> testClass) throws InitializationError {
super(testClass);
}
...
@Override
protected Class<? extends TestLifecycle> getTestLifecycleClass() {
return MyTestLifecycle.class;
}
public static class MyTestLifecycle extends DefaultTestLifecycle {
@Override
public Application createApplication(final Method method, final AndroidManifest appManifest) {
// run tests under our TestApplication
return new TestApplication();
}
}
...
}
您可以在org.robolectric.Config.properties文件中对其进行配置
application = <fully qualified name of the Application>