InjectionOverrideRule.kt 1.1 KB

1234567891011121314151617181920212223242526272829
  1. /*
  2. * Nextcloud - Android Client
  3. *
  4. * SPDX-FileCopyrightText: 2023 Álvaro Brey <alvaro@alvarobrey.com>
  5. * SPDX-FileCopyrightText: 2023 Nextcloud GmbH
  6. * SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
  7. */
  8. package com.nextcloud.test
  9. import android.app.Instrumentation
  10. import androidx.test.platform.app.InstrumentationRegistry
  11. import dagger.android.AndroidInjector
  12. import org.junit.rules.TestRule
  13. import org.junit.runner.Description
  14. import org.junit.runners.model.Statement
  15. class InjectionOverrideRule(private val overrideInjectors: Map<Class<*>, AndroidInjector<*>>) : TestRule {
  16. override fun apply(base: Statement, description: Description): Statement = object : Statement() {
  17. override fun evaluate() {
  18. val instrumentation: Instrumentation = InstrumentationRegistry.getInstrumentation()
  19. val testApp = instrumentation.targetContext.applicationContext as TestMainApp
  20. overrideInjectors.entries.forEach {
  21. testApp.addTestInjector(it.key, it.value)
  22. }
  23. base.evaluate()
  24. testApp.clearTestInjectors()
  25. }
  26. }
  27. }