In Java, the programmer can specify expected exceptions for JUnit test cases like this:
@Test(expected = ArithmeticException.class)
public void omg()
{
int bl
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!"))
}
}
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 }
}
}
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)
// ...
}
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")
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()
}
}
You can use KotlinTest for this.
In your test, you can wrap arbitary code with a shouldThrow block:
shouldThrow<ArithmeticException> {
// code in here that you expect to throw a ArithmeticException
}