Using this manual to test Coroutines. Writing a test that expected to throw exception crashes instead of passing the test. I wonder what i'm doing wrong.
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")
}
}
The test method above and the one below
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")
}
}
}
both of them crash even though
Note: Prefer to provide TestCoroutineScope when it does not complicate code since it will also elevate exceptions to test failures.
- Why both of them crash?
- Why the one with scope does not fail instead of crashing?