gpt4 book ai didi

unit-testing - 协程测试异常不会被 TestCoroutineDispatcher 和 TestCoroutineScope 处理

转载 作者:行者123 更新时间:2023-12-02 12:40:21 25 4
gpt4 key购买 nike

使用此 manual测试协程。编写一个预期会抛出异常的测试会崩溃而不是通过测试。我想知道我做错了什么。

    private val testDispatcher = TestCoroutineDispatcher()

@Before
fun setup() {
// provide the scope explicitly, in this example using a constructor parameter
Dispatchers.setMain(testDispatcher)
}

@After
fun cleanUp() {
Dispatchers.resetMain()
testDispatcher.cleanupTestCoroutines()
}

@Test(expected = RuntimeException::class)
fun testSomeFunctionWithException() = testDispatcher.runBlockingTest {
someFunctionWithException()
}


private fun someFunctionWithException() {
MainScope().launch {
throw RuntimeException("Failed via TEST exception")
}
}

上面和下面的测试方法
    private val testScope = TestCoroutineScope()
private lateinit var subject: Subject

@Before
fun setup() {
// provide the scope explicitly, in this example using a constructor parameter
subject = Subject(testScope)
}

@After
fun cleanUp() {
testScope.cleanupTestCoroutines()
}


@Test(expected = RuntimeException::class)
fun testFooWithException() = testScope.runBlockingTest {
subject.fooWithException()
}

class Subject(private val scope: CoroutineScope) {


fun fooWithException() {
scope.launch {
println("fooWithException() thread: ${Thread.currentThread().name}")
throw RuntimeException("Failed via TEST exception")
}
}
}

即使他们都崩溃了

Note: Prefer to provide TestCoroutineScope when it does not complicate code since it will also elevate exceptions to test failures.


  • 为什么两个都崩溃?
  • 为什么具有范围的那个不会失败而不是崩溃?
  • 最佳答案

    TestCoroutineScope用途 TestCoroutineExceptionHandler它将处理协程中抛出的所有异常,将它们收集到 uncaughtExceptions 中。列表,尽管第一个将在 cleanUp 期间被重新抛出或更具体地说,当 cleanupTestCoroutines()被调用,因此您必须对该异常执行一些操作以防止测试失败。

    @After
    fun cleanUp() {
    try {
    testScope.cleanupTestCoroutines()
    } catch (e: Exception) {
    //Do something here
    }
    }

    在测试期间,您可以检查 uncaughtExceptions列出你的断言:
    @Test(expected = RuntimeException::class)
    fun testFooWithException() = testScope.runBlockingTest {
    subject.fooWithException()
    assertEquals(1, uncaughtExceptions.size)
    assertEquals(uncaughtExceptions[0].message, "Failed via TEST exception")
    }

    关于unit-testing - 协程测试异常不会被 TestCoroutineDispatcher 和 TestCoroutineScope 处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61730593/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com