Skip to content

Commit eee46c5

Browse files
committed
Suppress reported exceptions in runTest
1 parent 29f8867 commit eee46c5

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

kotlinx-coroutines-test/common/src/TestBuilders.kt

+3-2
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,8 @@ public expect class TestResult
148148
* #### Reported exceptions
149149
*
150150
* Exceptions reported to the test coroutine scope via [TestCoroutineScope.reportException] will be thrown at the end.
151-
* By default, unless an explicit [TestExceptionHandler] is passed, this includes all unhandled exceptions.
151+
* By default, unless an explicit [TestExceptionHandler] is passed, this includes all unhandled exceptions. If the test
152+
* body also fails, the reported exceptions are suppressed by it.
152153
*
153154
* #### Uncompleted coroutines
154155
*
@@ -219,7 +220,7 @@ public fun runTest(
219220
} catch (e: UncompletedCoroutinesError) {
220221
// it's normal that some jobs are not completed if the test body has failed, won't clutter the output
221222
} catch (e: Throwable) {
222-
e.printStackTrace()
223+
it.addSuppressed(e)
223224
}
224225
throw it
225226
}

kotlinx-coroutines-test/common/test/RunTestTest.kt

+24
Original file line numberDiff line numberDiff line change
@@ -216,4 +216,28 @@ class RunTestTest {
216216
}
217217
}
218218
})
219+
220+
/** Tests that, when the test body fails, the reported exceptions are suppressed. */
221+
@Test
222+
fun testSuppressedExceptions() = testResultMap({
223+
try {
224+
it()
225+
fail("should not be reached")
226+
} catch (e: TestException) {
227+
assertEquals("w", e.message)
228+
val suppressed = e.suppressedExceptions +
229+
(e.suppressedExceptions.firstOrNull()?.suppressedExceptions ?: emptyList())
230+
assertEquals(3, suppressed.size)
231+
assertEquals("x", suppressed[0].message)
232+
assertEquals("y", suppressed[1].message)
233+
assertEquals("z", suppressed[2].message)
234+
}
235+
}, {
236+
runTest {
237+
reportException(TestException("x"))
238+
reportException(TestException("y"))
239+
reportException(TestException("z"))
240+
throw TestException("w")
241+
}
242+
})
219243
}

0 commit comments

Comments
 (0)