如何测试投掷的Kotlin Coroutine?
( kotlin 1.5.21,kotlinx-coroutines-test 1.5.0 )
请考虑 androidx.lifecycle.viewmodel
:
fun mayThrow(){
val handler = CoroutineExceptionHandler { _, t -> throw t }
vmScope.launch(dispatchers.IO + handler) {
val foo = bar() ?: throw IllegalStateException("oops")
withContext(dispatchers.Main) {
_someLiveData.value = foo
}
}
}
vmscope
对应于 ViewModelsCope
,在测试中,它被A testCoroutinesCope
代替。 dispatchers.io
是 dispatchers.io
的代理,在测试中,它是 testCoroutInedInedisPatcher
。在这种情况下,如果 bar()
返回null,则应用程序的行为是不确定的,因此,如果是这样,我希望它崩溃。现在我试图(JUNIT4)测试此代码:
@Test(expected = IllegalStateException::class)
fun `should crash if something goes wrong with bar`() {
tested.mayThrow()
}
测试失败是因为它应该测试的同样例外:
Exception in thread "Test worker @coroutine#1" java.lang.IllegalStateException: oops
// stack trace
Expected exception: java.lang.IllegalStateException
java.lang.AssertionError: Expected exception: java.lang.IllegalStateException
// stack trace
我感觉我在这里缺少一些很明显的东西...问题:是否是代码我的ViewModel是从Coroutine中抛出异常的正确方法,如果是,我该如何测试?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
功能
maythrow
具有太多职责,这就是为什么很难测试的原因。这是一个标准问题,并且存在标准处理(首先, 第二个):长话短说是应用单个责任原则。例如,将异常处理程序传递到功能
Function
mayThrow
has too many responsibilities, that is why it is hard to test. It is a standard problem and there are standard treatments (first, second): long story short is apply Single responsibility principle.For instance, pass exception handler to the function
如果没有其他作用,我可以建议将代码(将异常)移动到另一种方法并测试此方法:
或使用
junit jupiter
允许使用 /a>方法。例子:If nothing else works I can suggest to move the code, which throws an exception, to another method and test this method:
Or using
JUnit Jupiter
allows to test throwing Exceptions by usingassertThrows
method. Example: