Как проверить актеров Kotlin Coroutine - PullRequest
0 голосов
/ 28 июня 2019

Я реализовал актера, как в официальных документах 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 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), который по крайней мере превратит первый тест в зеленый, но тест исключения все равно не пройден.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...