Skip to content

Instantly share code, notes, and snippets.

@ken-itakura
Created April 2, 2021 04:02
Show Gist options
  • Save ken-itakura/d20b5b46c996d0c563fc8f5d02e1face to your computer and use it in GitHub Desktop.
Save ken-itakura/d20b5b46c996d0c563fc8f5d02e1face to your computer and use it in GitHub Desktop.
async function test with Kotlin, junit and Truth
import com.google.common.truth.Truth.assertThat // https://truth.dev/
import junit.framework.TestCase
import kotlinx.coroutines.*
import org.junit.Test
class SampleAsyncTest : TestCase() {
suspend fun sampleFunctionToTest(): String {
delay(1000)
return "failure"
}
@Test
fun testAsync() {
var failureMessage: String? = ""
// Exception in coroutine cannot be catched by general try-catch
// So define CoroutineExceptionHandler
// https://kotlinlang.org/docs/exception-handling.html#cancellation-and-exceptions
val coroutineExceptionHandler = CoroutineExceptionHandler { _, exception ->
failureMessage = exception.message
}
runBlocking { // wait testing function complete
GlobalScope.launch(coroutineExceptionHandler) {
// Call async function to Test
val sampleVal = async { sampleFunctionToTest() }
// assertThat the value as normal
// If it fails, it causes exception in coroutine
assertThat(sampleVal.await()).isEqualTo("success")
}.join()
}
// Check if there was no exception
assertThat(failureMessage).isEmpty()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment