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
?