如何在Koltin Coroutine测试中模拟False中的ISARTIVE值?
我想在这样的悬浮函数中介绍次循环之后,
suspend fun doWork(): Result<Any> {
while(isActive) {
/* ... do something */
return something
}
throw Exception("...")
}
这是一个真实代码的通用想法,我尝试了两件事来达到解决方案:
- 创建一个假作业,但是当我实现作业界面时,我找到了一些@InternalCoroutinesapi注释,因此,如果不可能,则
- 在这样的测试功能中创建一个内部coroutine,
@Test(expected = Exception::class)
fun `test when job is not active`() = coroutineDispatcher.runBlockingTest {
launch(coroutineContext) {
cancel()
val sut = doWork()
}
}
但最后一个为我提供了一个假阳性和jacoco,它没有接受。有什么想法或建议吗?
I would like to cover the throw line after the while loop in a suspend function like this
suspend fun doWork(): Result<Any> {
while(isActive) {
/* ... do something */
return something
}
throw Exception("...")
}
This is a generic idea of real code and I have tried two things to reach the solution:
- Create a fake job but when I implemented Job interface I found some @InternalCoroutinesApi annotations so if not possible go by this way
- Create an internal coroutine in the test function like this
@Test(expected = Exception::class)
fun `test when job is not active`() = coroutineDispatcher.runBlockingTest {
launch(coroutineContext) {
cancel()
val sut = doWork()
}
}
But this last one gives me a false positive and Jacoco it's not taking it. Any idea or suggestion?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这并不是真正的答案,但是您很有可能在这里根本不需要
ISACTIVE
。您可以只使用
while(true)
,然后在循环之后忘记投掷
。如果您在循环中有暂停功能调用,他们可能会自行检测取消。如果没有,您可以yart()
添加一些悬架点。请注意,
ISACTIVE
仅在当前的Coroutine上下文具有job
时才能正常工作,这可能并非总是如此(暂停Fun Main
不有工作,GlobalsCope
也没有工作。这就是为什么我建议拒绝coroutinecontext.isactive
和这个问题已打开。This is not really an answer, but there is a high chance you don't need
isActive
here at all.You could just use
while(true)
and forget about thethrow
after the loop. If you have suspend function calls in the loop, they will likely detect cancellation on their own. If not, you canyield()
to add some suspension points.Note that
isActive
only works correctly if the current coroutine context has aJob
, which might not always be the case (suspend fun main
doesn't have a job, nor doesGlobalScope
). This is one of the reasons why I suggested deprecatingCoroutineContext.isActive
and this issue was opened.我得到了解决方案。点第二,以创建内部的coroutine和取消的方式,可以使用错误的值进行
真正的线索 和正确的覆盖范围是将jacoco版本设置为Gradle中的最后一个版本
就这样。感谢大家试图帮助我。
I got the solution. Point two in a way to create an inner coroutine and cancel it was ok to get isActive with a false value
The real clue for getting the solution and right coverage was to set JaCoCo version to the last one in Gradle
That's all. Thank you to everybody for trying to help me.