bw_üezi
bw_üezi

Reputation: 4574

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 ...

Upvotes: 0

Views: 134

Answers (2)

k314159
k314159

Reputation: 11266

tyg's answer is correct, but I would advise against checking the exact wording of "expected... but was" in case it's changed in a future version of Kotest. You can just check that the exception message starts with the given clue:

    val error = shouldThrow<AssertionError> {
        withClue("whatever") {
            0 shouldBe 1
        }
    }
    error.message should startWith("whatever\n")

Upvotes: 0

tyg
tyg

Reputation: 15803

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.

Upvotes: 1

Related Questions