JUnit test. ~How to mock "throwable function" that...
# coroutines
a
JUnit test. How to mock "throwable function" that is called inside
async()
?
Copy code
/** org.mockito.kotlin.wheneverBlocking */
wheneverBlocking { worker.getValue() }.thenThrow(RuntimeException("Something went wrong!"))

/** io.mockk.coEvery */
coEvery { worker.getValue() } throws RuntimeException("Something went wrong!")
both
mockito
and
mockk
throws from
async
block instead of
await
Copy code
// function under test
// ...

val deferred = async {
    worker.getValue() // Throws here
}

try {
    val result = deferred.await()
} catch (e: Exception) {
    println("Caught")
}
Update: I finally figured out real cause (explanation in reply-thread) 😕
Exception got thrown from
await()
and captured by
catch block
as expected. The point of confusion is printed stack trace like it wasn't caught. (1st screenshot) The reason for stack trace been printed is "structured concurrency" or the way
Jobs
propagates their failures. While exception was caught it still do not saves
Job
from failure, so Job propagate this failure up to the first
parentJob
which is capable to handle it. If there are no such
parentJobs
then "top most" one just throw the original
cause
as is (2nd screenshot).
Another important note is that
EntityUnderTest
in real scenario runs under
Scope
with
SupervisorJob
while Test environment id driven by
runTest() {}
builder