在单元测试中调用Dispatchers.setMain()时出错

时间:2019-01-06 13:17:44

标签: android kotlin coroutine kotlinx.coroutines

已经开始尝试在JUnit单元测试中使用kotlinx-coroutines-testhttps://github.com/Kotlin/kotlinx.coroutines/blob/master/core/kotlinx-coroutines-test/README.md),但是当我调用Dispatchers.setMain()时出现以下错误

java.lang.IllegalArgumentException: TestMainDispatcher is not set as main dispatcher, have Main[missing, cause=java.lang.AbstractMethodError: kotlinx.coroutines.test.internal.TestMainDispatcherFactory.createDispatcher()Lkotlinx/coroutines/MainCoroutineDispatcher;] instead.

    at kotlinx.coroutines.test.TestDispatchers.setMain(TestDispatchers.kt:22)

我尝试调用Dispatchers.setMain(Dispatchers.Unconfined)并传递val mainThreadSurrogate = newSingleThreadContext("UI thread")。看起来问题根本不是传递值,而是在下面的mainDispatcher测试中出现了问题

public fun Dispatchers.setMain(dispatcher: CoroutineDispatcher) {
    require(dispatcher !is TestMainDispatcher) { "Dispatchers.setMain(Dispatchers.Main) is prohibited, probably Dispatchers.resetMain() should be used instead" }
    val mainDispatcher = Dispatchers.Main
    require(mainDispatcher is TestMainDispatcher) { "TestMainDispatcher is not set as main dispatcher, have $mainDispatcher instead." }
    mainDispatcher.setDispatcher(dispatcher)
}

2 个答案:

答案 0 :(得分:5)

尝试添加core作为对测试的依赖。它为我解决了这个问题。

public static class IEnumerableExt { // TKey combineFn((TKey Key, T Value) PrevKeyItem, T curItem): // PrevKeyItem.Key = Previous Key // PrevKeyItem.Value = Previous Item // curItem = Current Item // returns new Key public static IEnumerable<(TKey Key, T Value)> ScanPair<T, TKey>(this IEnumerable<T> src, TKey seedKey, Func<(TKey Key, T Value), T, TKey> combineFn) { using (var srce = src.GetEnumerator()) { if (srce.MoveNext()) { var prevkv = (seedKey, srce.Current); while (srce.MoveNext()) { yield return prevkv; prevkv = (combineFn(prevkv, srce.Current), srce.Current); } yield return prevkv; } } } // bool testFn(T prevItem, T curItem) // returns groups by sequential matching bool public static IEnumerable<IGrouping<int, T>> GroupByWhile<T>(this IEnumerable<T> src, Func<T, T, bool> testFn) => src.ScanPair(1, (kvp, cur) => testFn(kvp.Value, cur) ? kvp.Key : kvp.Key + 1) .GroupBy(kvp => kvp.Key, kvp => kvp.Value); public static T MaxBy<T, TKey>(this IEnumerable<T> src, Func<T, TKey> keySelector, Comparer<TKey> keyComparer) => src.Aggregate((a, b) => keyComparer.Compare(keySelector(a), keySelector(b)) > 0 ? a : b); public static T MaxBy<T, TKey>(this IEnumerable<T> src, Func<T, TKey> keySelector) => src.Aggregate((a, b) => Comparer<TKey>.Default.Compare(keySelector(a), keySelector(b)) > 0 ? a : b); }

答案 1 :(得分:3)

原来的问题是我正在使用旧版本的kotlinx-coroutines-core依赖项。当我更新到v1.1.0时,它开始工作了(感谢@vigit帮助触发该实现!)