Testing async exception in spring boot kotiln and coroutines

29 Views Asked by At

I have a web application with the following method written in kotlin using Spring Boot and Coroutines:

suspend fun runJob(request: JobRequest): String {
    .......
    CoroutineScope(Dispatchers.IO).launch {
       runCatching {
            .......
            someIoService.doSomething()
            .......
        }.onFailure{
            // print the issue and throw runtime exception
        }
    }
    ....
    return ....
}

I'm trying to write integration test using @SpringBootTest, runTest and kotest that tests a scenario when someIoService.doSomething() throws an exception:

@Test
fun `when doSomething fails then job fails`() = runTest {
  coEvery{mockSomeIoService.doSomething()} throws RunTimeException()
  webTestClient.post(.......)
  waitForJobToFinish() // poll on job status to either finish or fail
 //assert stuff
}

I tried using

shouldThrow<RunTimeException>{
  webTestClient.post(.......)
  waitForJobToFinish()
}

Also tried runCatching inside the test, or shouldThrowSoftly instead of shouldThrow but nothing seems to work because it's the async process that throws the exception and not the call to runJob itself.

is there any way I can test that?

edit: I just found out that using runBlocking and runCatching inside instead of runTest works. but I'd like to use runTest

is there a way to achieve the functionality of runCatching in runTest

0

There are 0 best solutions below