I'm not sure how to create a custom matcher that would verify the information stored in a custom exception. I need a custom matcher because the way exceptions are stored in this system that I'm working on is they are added up on a list. Now I need to verify that errors on that list and the error message.
I'm pretty sure this was already done before, I'm just not sure where to look for it
Try using sameBeanAs
matcher from shazamcrest. It is able to compare two objects by serializing their fields to JSON. No getters, public fields or any annotations on the production class are needed. All you need to do is just create the expected object and compare it against actual object:
com.shazam.shazamcrest.MatcherAssert.assertThat(actualException, is(sameBeanAs(expectedException))
Note: it is important that you use MatcherAssert
from shazamcrest and not from hamcrest, otherwise sameBeanAs
gives bad diagnostics.
I am not sure how comparing exceptions will work in regards to stack trace which is just a field in Throwable
. If it is a problem you may have to ignore specific fields when using sameBeanAs
.
If you still want to write your own hamcrest matcher, here is the tutorial.