Properly enable AccessibilityChecks for multi-file test suite

I'm trying to wrap my head around the proper way to set up Android Espresso's AccessibilityChecks. Documentation suggests I just call AccessibilityChecks.enable() in a @Before setup method. The problem is, if you have more than one test in that class, the second test run will throw an exception warning that AccessibilityChecks is already enabled. You can fix this by instead calling it in a @BeforeClass static setup method. However, if you have another test that should have AccessbililtyChecks enabled, you'll get the same error. AccessibilityChecks.enable() creates a global view assertion that can't be disabled or removed, as far as I can tell.

My current workaround is to have an Espresso test that runs before all the other ones (AAA_AccessibilityTest.java), and I don't enable it anywhere else.

The problem with that is if I'm focusing on a particular test set, the Accessibility Checks won't run, because that test isn't included.

Maybe someone from Android can weigh in here, but I haven't been able to find any working examples on Github or elsewhere that shows this being used in a non-trivial test suite.

The intent of AccessibilityChecks.enable() is awesome, but the implementation seems completely broken without a way to disable() them after we enable() them. Am I missing something? How can I use this in a reliable and sane way?


You can enable it in a custom test runner (in Java):

public class AccessibilityChecksTestRunner extends AndroidJUnitRunner {
  static {
    AccessibilityChecks.enable();
  }
}

or in Kotlin

 class AccessibilityChecksTestRunner : AndroidJUnitRunner() {
    init {
       AccessibilityChecks.enable()
    }
 }

Use in build.gradle:

testInstrumentationRunner "com.example.AccessibilityChecksTestRunner"