In Kotlin with JUnit5 we can use assertFailsWith
In Java with JUnit5 you can use assertThrows
In Java, if I want to separate the declaration of an executable from the execution itself, in order to clarify the tests in a Given-Then-When form, we can use JUnit5 assertThrows
like this:
@Test
@DisplayName("display() with wrong argument command should fail" )
void displayWithWrongArgument() {
// Given a wrong argument
String arg = "FAKE_ID"
// When we call display() with the wrong argument
Executable exec = () -> sut.display(arg);
// Then it should throw an IllegalArgumentException
assertThrows(IllegalArgumentException.class, exec);
}
In Kotlin we can use assertFailsWith
:
@Test
fun `display() with wrong argument command should fail`() {
// Given a wrong argument
val arg = "FAKE_ID"
// When we call display() with the wrong argument
// ***executable declaration should go here ***
// Then it should throw an IllegalArgumentException
assertFailsWith<CrudException> { sut.display(arg) }
}
But, how we can separate the declaration and the execution in Kotlin with assertFailsWith
?
Using Kotlin's assertFailsWith Method The Kotlin standard library also provides a function to test exceptions. We can use the assertFailsWith method to assert that a block of code fails with an exception type. In the example above, the assertion passes when the block throws an ArrayIndexOutOfBoundsException.
In JUnit 5, to write the test code that is expected to throw an exception, we should use Assertions. assertThrows(). In the given test, the test code is expected to throw an exception of type ApplicationException or its subtype. Note that in JUnit 4, we needed to use @Test(expected = NullPointerException.
When using JUnit 4, we can simply use the expected attribute of the @Test annotation to declare that we expect an exception to be thrown anywhere in the annotated test method. In this example, we've declared that we're expecting our test code to result in a NullPointerException.
Just declare a variable like you did in Java:
@Test
fun `display() with wrong argument command should fail`() {
// Given a wrong argument
val arg = "FAKE_ID"
// When we call display() with the wrong argument
val block: () -> Unit = { sut.display(arg) }
// Then it should throw an IllegalArgumentException
assertFailsWith<CrudException>(block = block)
}
in my example you can do like this :
@Test
fun divide() {
assertThrows(
ArithmeticException::class.java,
{ MathUtils.divide(1, 0) },
"divide by zero should trow"
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With