p3quod
p3quod

Reputation: 1679

Kotlin and JUnit 5 assert an exception is thrown: separate declaration and execution with assertFailsWith

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?

Upvotes: 11

Views: 14051

Answers (3)

jazz64
jazz64

Reputation: 339

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.

Upvotes: 1

Sana Ebadi
Sana Ebadi

Reputation: 7220

in my example you can do like this :

@Test
fun divide() {
    assertThrows(
        ArithmeticException::class.java,
        { MathUtils.divide(1, 0) },
        "divide by zero should trow"
    )
}

Upvotes: 6

awesoon
awesoon

Reputation: 33651

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)
}

Upvotes: 12

Related Questions