Search code examples
testingkotlinkoin

KoinAppAlreadyStartedException: A Koin Application has already been started


Using koin-2.0.1 for Android testing and unable to test all 3 test together though each test passes separately.

class NumberFormatterUtilImplTest : KoinTest {

    private val numberFormatterUtil: NumberFormatterUtilImpl by inject()

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

    @Test
    fun `does formatter returns two digit faction if supplied one digit value`() {
        val result = numberFormatterUtil.getAdjustedCurrencyRate(18.0)
        Assert.assertEquals(result, 18.00, 1.0)
    }

    @Test
    fun `does formatter returns two digit faction if supplied multiple digits value`() {
        val result = numberFormatterUtil.getAdjustedCurrencyRate(18.12343)
        Assert.assertEquals(result, 18.12, 1.0)
    }

    @Test
    fun `does formatter returns rounded two digit faction if supplied multiple digits value`() {
        val result = numberFormatterUtil.getAdjustedCurrencyRate(18.12876)
        Assert.assertEquals(result, 18.13, 1.0)
    }
}

running class level testing resulting below:

org.koin.core.error.KoinAppAlreadyStartedException: A Koin Application has already been started

any input would be helpful, thanks.


Solution

  • As an alternative to the @After approach, you can also use AutoCloseKoinTest. As described in the docs:

    Extended Koin Test - embed autoclose @after method to close Koin after every test

    Instead of extending KoinTest, you can extend AutoCloseKoinTest and it will do the after test for you.