10

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,449
  • 3
  • 13
  • 15
  • 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

3 Answers3

11

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
  • 32,469
  • 11
  • 74
  • 99
4

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
  • 6,656
  • 2
  • 44
  • 44
0

I really agree with p3quod's claim on the Given/When/Then (or Arrange/Act/Assert) pattern.

My way in Kotlin:

import org.junit.jupiter.api.Assertions.assertThrows
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.function.Executable

@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 executable = Executable { sut.display(arg) }

    // Then it should throw an IllegalArgumentException
    assertThrows(IllegalArgumentException::class.java, executable)
}

Is there a better way, more Kotlin like, let me know.

jazz64
  • 199
  • 1
  • 5
  • 12