willowtreeapps / assertk

assertions for kotlin inspired by assertj
MIT License
760 stars 85 forks source link

Attempt to propagate a source throwable as a cause #460

Closed JakeWharton closed 1 year ago

JakeWharton commented 1 year ago

This ensures that the full stacktrace can be seen to help identify the underlying source of a mismatch.

Consider the following two tests:

@Test fun demo1() {
  assertThat { someFunction() }
    .isFailure()
    .isInstanceOf(IllegalStateException::class)
}
@Test fun demo2() {
  assertThat { someFunction() }
    .isFailure()
    .hasMessage("failure!")
}
fun someFunction() {
  deepFunction()
}
fun deepFunction() {
  throw AssertionError("oh no!!!!!")
}

Demo 1's failure before:

org.opentest4j.AssertionFailedError: expected to be instance of:<class java.lang.IllegalStateException> but had class:<class java.lang.AssertionError> (Failure(java.lang.AssertionError: oh no!!!!!))
    at app//test.assertk.FailureTest.demo1(FailureTest.kt:56)
    ... 43 more

Demo 1's failure after:

org.opentest4j.AssertionFailedError: expected to be instance of:<class java.lang.IllegalStateException> but had class:<class java.lang.AssertionError> (Failure(java.lang.AssertionError: oh no!!!!!))
    at app//test.assertk.FailureTest.demo1(FailureTest.kt:56)
    ... 43 more
Caused by: java.lang.AssertionError: oh no!!!!!
    at test.assertk.FailureTest.deepFunction(FailureTest.kt:70)
    at test.assertk.FailureTest.someFunction(FailureTest.kt:66)
    at test.assertk.FailureTest.demo1(FailureTest.kt:54)
    ... 43 more

Demo 2's failure before:

org.opentest4j.AssertionFailedError: expected [message]:<"[failure]!"> but was:<"[oh no!!!!]!"> (Failure(java.lang.AssertionError: oh no!!!!!))
    at app//test.assertk.FailureTest.demo2(FailureTest.kt:61)
    ... 43 more

Demo 2's failure after:

org.opentest4j.AssertionFailedError: expected [message]:<"[failure]!"> but was:<"[oh no!!!!]!"> (Failure(java.lang.AssertionError: oh no!!!!!))
    at app//test.assertk.FailureTest.demo2(FailureTest.kt:62)
    ... 43 more
Caused by: java.lang.AssertionError: oh no!!!!!
    at test.assertk.FailureTest.deepFunction(FailureTest.kt:70)
    at test.assertk.FailureTest.someFunction(FailureTest.kt:66)
    at test.assertk.FailureTest.demo2(FailureTest.kt:60)
    ... 43 more

With the causes attached it's much easier to locate the source of the underlying problem.

Closes #456