簡體   English   中英

如何測試 Kotlin 協程 actor

[英]How to test Kotlin Coroutine actors

我已經在官方kotlinx.coroutines 文檔中實現了一個演員。 現在我必須在我的儀器測試中測試它們,但我總是得到

IllegalStateException: This job has not completed yet

這是我的測試代碼:

@RunWith(AndroidJUnit4::class)
@ExperimentalCoroutinesApi
class ExampleInstrumentedTest {

    @Test
    fun testIncrease() = runBlockingTest {
        val counter = Counter()
        for (i in 0..10) {
            counter.increase()
        }
    }

    @Test
    fun testException() = runBlockingTest {
        val counter = Counter()
        try {
            for (i in 0..11) {
                counter.increase()
            }
            Assert.fail()
        } catch (e: Exception) {
            // All good if the exception was thrown
        }
    }
}

這是演員:

sealed class CounterMsg
object IncCounter : CounterMsg()
class GetCounter(val response: CompletableDeferred<Int>) : CounterMsg()

class CounterActor {
    private val actor = GlobalScope.actor<CounterMsg> {
        var counter = 0
        for (msg in channel) {
            when (msg) {
                is IncCounter -> if (counter < 10) counter++ else throw RuntimeException()
                is GetCounter -> msg.response.complete(counter)
            }
        }
    }

    suspend fun send(message: CounterMsg) = actor.send(message)
}

class Counter {
    private val actor = CounterActor()
    suspend fun increase() = actor.send(IncCounter)
}

我的依賴:

implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.40"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-jdk8:1.3.0-M1"
androidTestImplementation "androidx.test.ext:junit:1.1.1"
androidTestImplementation "androidx.test:runner:1.2.0"
androidTestImplementation "org.jetbrains.kotlin:kotlin-test:1.3.40"
androidTestImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.3.0-M1"

我已經嘗試過GlobalScope.actor<CounterMsg>(Dispatchers.Unconfined)至少會將第一個測試變為綠色,但異常測試仍然失敗。

顯然,它正在進行一些小的更改:

  • 使用cancel()而不是在 actor 中拋出異常
  • 使用runBlocking而不是runBlockingTest

我通過添加以下規則解決了:

@get: Rule
var instantExecutorRule = InstantTaskExecutorRule()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM