kotlinjunit4android-junitandroidjunitrunner

How to apply a Rule to all test cases in a AndroidJUnitRunner?


I'm trying to apply a TestWatcher as a rule across all my test cases run by a particular runner.

MetadataCollector:

class MetadataCollector : TestWatcher() { ... }

TestRunner:

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)
  }
}

All of my test classes currently require MetadataCollector() to be initialized as a Rule:

Test Class:

@JvmField @Rule val collector = MetadataCollector()

Is there a way I can create an instance of this rule automatically to each test case from the runner? Ideally, this is to avoid duplicating this @Rule creation in every single Test Class.

I am unfortunately stuck with JUnit 4 at the moment. :(


Solution

  • There is a better way to do this, by injecting an instance of RunListener into your test runner. In your gradle config, you need to:

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

    And in code, create a RunListenerClassName to implement the corresponding hooks

    class MyRunListener : RunListener() { 
       // impl
    }