Search code examples
androidunit-testingkotlinjunitkoin

Calling startKoin() once before launching all unit tests and stopKoin() once after all tests finish


I have several test classes implementing KoinTest interface, and in every one of them I have the same code:

@Before
fun setUp() {
    startKoin { modules(appModule) }
}

@After
fun tearDown() {
    stopKoin()
}

Is it possible to call startKoin() before all these tests, and after the tests call stopKoin(), so I can remove above code from every test class? Or maybe it would be strongly discouraged for some reason?

I see that in docs here they have written 'For each test, we start startKoin() and close Koin context closeKoin().', but I don't know if this is the only valid way to go.


Solution

  • You can use a TestRule. Create a test rule for Koin.

    class KoinTestRule : TestRule {
    
       override fun apply(base: Statement, description: Description): Statement {
           return object : Statement() {
    
               override fun evaluate() {
    
                   startKoin { modules(appModule) }
    
                   base.evaluate()
    
                   stopKoin()
               }
            }
        }
    }
    

    Create BaseKoinTest that implements KoinTest interface and add the rule to this class. All the test classes that require Koin can extend from this class.

    abstract class BaseKoinTest : KoinTest {
    
        @get:Rule
        val koinTestRule = KoinTestRule()
    }