7

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?

p3quod
  • 1,131
  • 11
  • 14
  • JUnit 5 has Kotlin support for built-in assertions - see https://junit.org/junit5/docs/current/user-guide/#writing-tests-assertions-kotlin – mkobit Apr 28 '19 at 06:37

2 Answers2

9

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)
}
awesoon
  • 30,028
  • 9
  • 67
  • 92
3

in my example you can do like this :

@Test
fun divide() {
    assertThrows(
        ArithmeticException::class.java,
        { MathUtils.divide(1, 0) },
        "divide by zero should trow"
    )
}
Sana Ebadi
  • 5,750
  • 1
  • 38
  • 42