Test expected exceptions in Kotlin

fredoverflow picture fredoverflow · May 19, 2015 · Viewed 39.6k times · Source

In Java, the programmer can specify expected exceptions for JUnit test cases like this:

@Test(expected = ArithmeticException.class)
public void omg()
{
    int blackHole = 1 / 0;
}

How would I do this in Kotlin? I have tried two syntax variations, but none of them worked:

import org.junit.Test

// ...

@Test(expected = ArithmeticException) fun omg()
    Please specify constructor invocation;
    classifier 'ArithmeticException' does not have a companion object

@Test(expected = ArithmeticException.class) fun omg()
                            name expected ^
                                            ^ expected ')'

Answer

fredoverflow picture fredoverflow · Jun 1, 2015

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)
    // ...
}