首页 > 解决方案 > 如何将规则应用于 AndroidJUnitRunner 中的所有测试用例?

问题描述

我正在尝试在由特定跑步者运行的所有测试用例中应用 TestWatcher 作为规则。

元数据收集器:

class MetadataCollector : TestWatcher() { ... }

测试运行者:

class TestRunner : AndroidJUnitRunner() {

  override fun onCreate(arguments: Bundle?) {
    super.onCreate(arguments)
  }

  override fun newApplication(cl: ClassLoader?, className: String?, context: Context?): Application {
    return super.newApplication(cl, TestApplication::class.java.name, context)
  }
}

我所有的测试类目前都需要MetadataCollector()初始化为规则:

测试类:

@JvmField @Rule val collector = MetadataCollector()

有没有办法可以从运行器自动为每个测试用例创建此规则的实例?理想情况下,这是为了避免@Rule在每个单独的测试类中重复这个创建。

不幸的是,我现在被JUnit 4困住了。:(

标签: kotlinjunit4android-junitandroidjunitrunner

解决方案


有一种更好的方法可以做到这一点,将 RunListener 的一个实例注入到您的测试运行器中。在您的 gradle 配置中,您需要:

defaultConfig.testInstrumentationRunner = "com.mypackage.MyTestRunnerClassName"
defaultConfig.testInstrumentationRunnerArgument("listener", "com.mypackage.MyRunListenerClassName")

并且在代码中,创建一个RunListenerClassName来实现对应的hook

class MyRunListener : RunListener() { 
   // impl
}

推荐阅读