https://kotlinlang.org logo
#coroutines
Title
# coroutines
b

Brendan Campbell-hartzell

08/13/2021, 4:54 AM
I'm trying to test that my code correctly responds if a launched coroutine fails, but the failure in the coroutine causes subsequent tests to fail due to a "Delayed Exception." If I try to handle the exception in the test code, then the failure won't propagate to my prod code. I'm not sure how to catch an error from the prod code so that the tests aren't failing due to the intended test error. Any ideas? Code in thread.
Test (which doesn't fail, but subsequent tests fail because of this error)
Copy code
fun `should enable inputs`() {
    val job by lazy {
        CoroutineScope(Dispatchers.Default).launch {
            error("Intended async error")
        }
    }

    behavior = { job }

    interact {
        view.nameInput.text = "Banana"
        view.timeInput.valueFactory.value = 0L
        view.submitButton.fire()
    }

    runBlocking {
        job.join()
    }

    assertThat(view.nameInput).isEnabled
    assertThat(view.timeInput).isEnabled
}
Prod code:
Copy code
private fun submit() {
        nameInput.isDisable = true
        timeInput.isDisable = true

        val nonBlankName = NonBlankString.create(nameInput.text) ?: return
        CoroutineScope(Dispatchers.JavaFx).launch {
            try {
                createStoryEventController.createStoryEvent(nonBlankName).join()
            } catch (t: Throwable) {

            }

            nameInput.isDisable = false
            timeInput.isDisable = false
        }/*
        createStoryEventController.createStoryEvent(nonBlankName).invokeOnCompletion { potentialFailure ->
            runBlocking {
                nameInput.isDisable = false
                timeInput.isDisable = false
            }
        }*/
    }
The createStoryEventController returns a
Job
and the
behavior
property in the tests is what's being called/returned by the mocked createStoryEventController
On reading more of the documentation, I was able to get the tests to stop failing (unexpectedly, that is) by providing a default
CoroutineExceptionHandler
. For anyone else curious, here's where I found it: https://kotlinlang.org/docs/exception-handling.html#cancellation-and-exceptions
2 Views