Test expected exceptions in Kotlin

Kotlin has its own test helper package that can help to do this kind of unittest.

Your test can be very expressive by use assertFailWith:

@Test
fun test_arithmethic() {
    assertFailsWith<ArithmeticException> {
        omg()
    }
}

The Kotlin translation of the Java example for JUnit 4.12 is:

@Test(expected = ArithmeticException::class)
fun omg() {
    val blackHole = 1 / 0
}

However, JUnit 4.13 introduced two assertThrows methods for finer-granular exception scopes:

@Test
fun omg() {
    // ...
    assertThrows(ArithmeticException::class.java) {
        val blackHole = 1 / 0
    }
    // ...
}

Both assertThrows methods return the expected exception for additional assertions:

@Test
fun omg() {
    // ...
    val exception = assertThrows(ArithmeticException::class.java) {
        val blackHole = 1 / 0
    }
    assertEquals("/ by zero", exception.message)
    // ...
}

You can use @Test(expected = ArithmeticException::class) or even better one of Kotlin's library methods like failsWith().

You can make it even shorter by using reified generics and a helper method like this:

inline fun <reified T : Throwable> failsWithX(noinline block: () -> Any) {
    kotlin.test.failsWith(javaClass<T>(), block)
}

And example using the annotation:

@Test(expected = ArithmeticException::class)
fun omg() {

}

You can use Kotest for this.

In your test, you can wrap arbitrary code with a shouldThrow block:

shouldThrow<ArithmeticException> {
  // code in here that you expect to throw a ArithmeticException
}