Include actual exception when `shouldThrowTheException` fails
See original GitHub issueActual situation
When a should throw the exception fails, the message states:
Expected foo.bar.TheExpectedException to be thrown expected:<class [foo.bar.TheExpected]Exception> but was:<class [kotlin.KotlinNullPointer]Exception>
Then I can see the stack trace of that ComparisonFailure (at least, in the IDE).
Problem
That indicates only the point of failure in the test (the assertion itself), but does not give me any information about the exception that did occur in reality (that was not expected). I need then to trace and/or modify temporarily my test code so it just fails (remove the assertion) and then I can see what happened.
Proposition
Include the actual exception as a cause of the thrown ComparisonFailure. That way, we can look at the stack trace to know exactly what happened instead of our expected exception.
In Exceptions.kt:
Before:
else throw ComparisonFailure("Expected ${expectedException.javaObjectType} to be thrown", "${expectedException.javaObjectType}", "${e.javaClass}")
After:
else throw ComparisonFailure("Expected ${expectedException.javaObjectType} to be thrown", "${expectedException.javaObjectType}", "${e.javaClass}", e)
That logic should/could be applied to every assertions on exceptions, including the withMessage and withCause.
After effect
From the IDE, we can then click on the stack trace of the exception that caused the assertion to fail to be brought to the line that caused it in the code AND know exactly what happened from its message.
Issue Analytics
- State:
- Created 6 years ago
- Comments:14 (4 by maintainers)

Top Related StackOverflow Question
I will de-a assign myself from it. I haven’t used Kotlin in almost 2 years. My focus is on completely different things now. My apologies for never completing this change.
This looks like a really nice addition.
ComparisonFailureis a type from junit, so we wouldn’t be able to add a constructor. But maybe subtyping it works.I initially chose to use the junit exceptions because the IDEs I use (IntelliJ and Eclipse) recognize them and can show a specific window (like a diff window for
assertEqualsfailures).However, the diff window wouldn’t be very useful here, as it just shows the two types.
I`d appreciate a pull request, because I don’t have a lot time in June at the moment, but would gladly review, merge and release it 😃 Otherwise I can look into it in July