如何测试Kotlin协程演员

时间:2019-06-28 06:30:03

标签: android kotlin kotlin-coroutines kotlinx.coroutines.channels

我已经像kotlinx.coroutines docs的官方角色中扮演了一个演员。现在,我必须在仪器化测试中对其进行测试,但我总是得到

IllegalStateException: This job has not completed yet

这是我的测试代码:

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

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

    @Test
    fun testException() = runBlockingTest {
        val counter = Counter()
        try {
            for (i in 0 until 11) {
                counter.increase()
            }
            Assert.fail()
        } catch (e: IllegalArgumentException) {
            // 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) throw IllegalArgumentException() else counter++
                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),这至少会使第一个测试变为绿色,但是异常测试仍然失败。

2 个答案:

答案 0 :(得分:0)

显然,它正在进行一些小的更改:

  • 使用cancel()而不是在actor中引发异常
  • 使用runBlocking代替runBlockingTest

答案 1 :(得分:0)

我通过添加以下规则解决了:

@get: Rule
var instantExecutorRule = InstantTaskExecutorRule()