Test expected exceptions in Kotlin

Unit TestingKotlinTestingExceptionJunit4

Unit Testing Problem Overview


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 ')'

Unit Testing Solutions


Solution 1 - Unit Testing

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

Solution 2 - Unit Testing

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()
    }
}

Solution 3 - Unit Testing

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() {

}

Solution 4 - Unit Testing

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
}

Solution 5 - Unit Testing

You can also use generics with kotlin.test package:

import kotlin.test.assertFailsWith 

@Test
fun testFunction() {
    assertFailsWith<MyException> {
         // The code that will throw MyException
    }
}

Solution 6 - Unit Testing

JUnit5 has kotlin support built in.

import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows

class MyTests {
    @Test
    fun `division by zero -- should throw ArithmeticException`() {
        assertThrows<ArithmeticException> {  1 / 0 }
    }
}

Solution 7 - Unit Testing

Nobody mentioned that assertFailsWith() returns the value and you can check exception attributes:

@Test
fun `my test`() {
        val exception = assertFailsWith<MyException> {method()}
        assertThat(exception.message, equalTo("oops!"))
    }
}

Solution 8 - Unit Testing

Assert extension that verifies the exception class and also if the error message match.

inline fun <reified T : Exception> assertThrows(runnable: () -> Any?, message: String?) {
try {
    runnable.invoke()
} catch (e: Throwable) {
    if (e is T) {
        message?.let {
            Assert.assertEquals(it, "${e.message}")
        }
        return
    }
    Assert.fail("expected ${T::class.qualifiedName} but caught " +
            "${e::class.qualifiedName} instead")
}
Assert.fail("expected ${T::class.qualifiedName}")

}

for example:

assertThrows<IllegalStateException>({
        throw IllegalStateException("fake error message")
    }, "fake error message")

Solution 9 - Unit Testing

org.junit.jupiter.api.Assertions.kt

/**
 * Example usage:
 * ```kotlin
 * val exception = assertThrows<IllegalArgumentException>("Should throw an Exception") {
 *     throw IllegalArgumentException("Talk to a duck")
 * }
 * assertEquals("Talk to a duck", exception.message)
 * ```
 * @see Assertions.assertThrows
 */
inline fun <reified T : Throwable> assertThrows(message: String, noinline executable: () -> Unit): T =
        assertThrows({ message }, executable)

Solution 10 - Unit Testing

This simple sample worked in the 4.13.2 version of Junit

    @Test
    fun testZeroDividing(){
        var throwing = ThrowingRunnable {  /*call your method here*/ Calculator().divide(1,0) }
        assertThrows(/*define your exception here*/ IllegalArgumentException::class.java, throwing)
    }

Solution 11 - Unit Testing

Another version of syntaxis using kluent:

@Test
fun `should throw ArithmeticException`() {
    invoking {
        val backHole = 1 / 0
    } `should throw` ArithmeticException::class
}

Solution 12 - Unit Testing

Firt steps is to add (expected = YourException::class) in test annotation

@Test(expected = YourException::class)

Second step is to add this function

private fun throwException(): Boolean = throw YourException()

Finally you will have something like this:

@Test(expected = ArithmeticException::class)
fun `get query error from assets`() {
    //Given
    val error = "ArithmeticException"

    //When
    throwException()
    val result =  omg()

    //Then
    Assert.assertEquals(result, error)
}
private fun throwException(): Boolean = throw ArithmeticException()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfredoverflowView Question on Stackoverflow
Solution 1 - Unit TestingfredoverflowView Answer on Stackoverflow
Solution 2 - Unit TestingMichele d'AmicoView Answer on Stackoverflow
Solution 3 - Unit TestingKirill RakhmanView Answer on Stackoverflow
Solution 4 - Unit TestingsksamuelView Answer on Stackoverflow
Solution 5 - Unit TestingMajidView Answer on Stackoverflow
Solution 6 - Unit TestingFrank NeblungView Answer on Stackoverflow
Solution 7 - Unit TestingSvetopolkView Answer on Stackoverflow
Solution 8 - Unit TestingYanay HollanderView Answer on Stackoverflow
Solution 9 - Unit TestingBraian CoronelView Answer on Stackoverflow
Solution 10 - Unit TestingAli DoranView Answer on Stackoverflow
Solution 11 - Unit TestingalexlzView Answer on Stackoverflow
Solution 12 - Unit TestingCabezasView Answer on Stackoverflow