对不同的测试使用不同的测试运行器
Using Different Test Runners For Different Tests
我正在使用 Dagger 2
并尝试在测试时提供不同的依赖项。
我可以为测试提供不同的依赖项,但不幸的是,这些依赖项适用于 androidTest
目录中的所有测试。
我通过指定使用 TestAppModule
的 TestAppComponent
来做到这一点。在扩展我的 AndroidApplication
的 TestApplication
中,我提供 TestAppComponent
而不是真正的 AppComponent
。然后我有 TestRunner
扩展 newApplication
方法,如下所示:
@Override
public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
return super.newApplication(cl, TestApplication.class.getName(), context);
}
然后为了使用这个跑步者,我将当前跑步者替换为以下内容:
testInstrumentationRunner "com.company.myapp.TestRunner"
我的问题
如何为不同的测试使用不同的 component/application/test 运行程序,而不是为每个测试使用相同的运行程序?我可能想在一个测试中模拟一个依赖项,但在另一个测试中不模拟?
我在博客 post 中找到了解决此问题的方法。它绕过创建自定义运行器,而是使用 Rule
在加载的 Application
中设置不同的组件。这意味着您可以为每个测试提供不同的组件class,这正是我想要做的。
可以找到 Ribot 实验室人员的博客 post here
我正在使用 Dagger 2
并尝试在测试时提供不同的依赖项。
我可以为测试提供不同的依赖项,但不幸的是,这些依赖项适用于 androidTest
目录中的所有测试。
我通过指定使用 TestAppModule
的 TestAppComponent
来做到这一点。在扩展我的 AndroidApplication
的 TestApplication
中,我提供 TestAppComponent
而不是真正的 AppComponent
。然后我有 TestRunner
扩展 newApplication
方法,如下所示:
@Override
public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
return super.newApplication(cl, TestApplication.class.getName(), context);
}
然后为了使用这个跑步者,我将当前跑步者替换为以下内容:
testInstrumentationRunner "com.company.myapp.TestRunner"
我的问题
如何为不同的测试使用不同的 component/application/test 运行程序,而不是为每个测试使用相同的运行程序?我可能想在一个测试中模拟一个依赖项,但在另一个测试中不模拟?
我在博客 post 中找到了解决此问题的方法。它绕过创建自定义运行器,而是使用 Rule
在加载的 Application
中设置不同的组件。这意味着您可以为每个测试提供不同的组件class,这正是我想要做的。
可以找到 Ribot 实验室人员的博客 post here