Search code examples
kotlinkotest

How to explain unexpected Kotest test result


Writing a test where I force an AssertionError and wrap it with withClue to assign a custom error message. So far anything as expected but than the actual intended assertion is if the actual custom error message was thrown as expected. the result is a bit unexpected.

So in the following code snippets everything works as expected but result of shouldThrowWithMessage is unexpected.

the code snippet I tried:

class MyTest : FunSpec({
    context("test context") {
        test("test unexpected fails") {
            shouldThrowWithMessage<AssertionError>("whatever") {
                withClue("whatever") {
                    0 shouldBe 1
                }
            }
        }
    }
})

Stacktrace

Expected exception message whatever but was whatever
java.lang.AssertionError: Expected exception message whatever but was whatever
expected:<1> but was:<0> instead.
    at ...
Caused by: io.kotest.assertions.AssertionFailedError: whatever
expected:<1> but was:<0>
    at ...

Solution

  • withClue doesn't replace the assertion message. From the documentation:

    Add clue as additional info to the assertion error message

    So, when you want shouldThrowWithMessage to match the assertion, it should look like this:

    shouldThrowWithMessage<AssertionError>("whatever\nexpected:<1> but was:<0>") {
        withClue("whatever") {
            0 shouldBe 1
        }
    }
    

    The whatever\n part is the part that was added by the clue (the clue is separated with a newline, hence the \n), the part expected:<1> but was:<0> is the original assertion message.