KoinAppAlreadyStartedException:Koin 应用程序已经启动

Fai*_*sal 5 testing kotlin koin

使用 koin-2.0.1 进行 Android 测试,尽管每个测试分别通过,但无法同时测试所有 3 个测试。

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

运行类级别测试结果如下:

org.koin.core.error.KoinAppAlreadyStartedException: A Koin Application has already been started
Run Code Online (Sandbox Code Playgroud)

任何输入都会有帮助,谢谢。

laa*_*lto 17

一种常见的做法是将@Before设置与@After清理配对。您可以stopKoin()在那里打电话,以便下一个电话startKoin()再次工作:

@After
fun tearDown() {
    stopKoin()
}
Run Code Online (Sandbox Code Playgroud)

  • 对我不起作用,必须执行“if (KoinContextHandler.getOrNull() == null) { startKoin...” (3认同)

Ker*_*ker 11

作为该@After方法的替代方法,您还可以使用AutoCloseKoinTest. 如文档中所述

扩展 Koin 测试 - 嵌入 autoclose @after 方法以在每次测试后关闭 Koin

相反延伸KoinTest,你可以扩展AutoCloseKoinTest和测试后,你会做的。

  • 链接不起作用。尝试了 @After 和 AutoCloseKoinTest,但没有一个解决方案有效。不断收到相同的错误 (2认同)

Bur*_*rtK 7

在 @Before 和 @After 方法上调用 stopKoin() ,如下所示:

import com.my.example.appModule
import android.os.Build
import androidx.test.core.app.ApplicationProvider
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.koin.android.ext.koin.androidContext
import org.koin.core.context.startKoin
import org.koin.core.context.stopKoin
import org.koin.test.KoinTest
import org.koin.test.inject
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.util.*

@Config(sdk = [Build.VERSION_CODES.LOLLIPOP])
@RunWith(RobolectricTestRunner::class)
class SomeRepositoryTest: KoinTest {

    // Return Completable of RxJava
    private val repository: SomeRepository by inject()

    @Before
    fun before() {
        stopKoin() // to remove 'A Koin Application has already been started'
        startKoin {
            androidContext(ApplicationProvider.getApplicationContext())
            modules(appModule)
        }
    }

    @After
    fun after() {
        stopKoin()
    }

    @Test
    fun testSomething() {

        repository.insert("data").blockingAwait()

        assert(true)
    }
}
Run Code Online (Sandbox Code Playgroud)