mystarrocks
mystarrocks

Reputation: 4088

Junit ExpectedException: expect an exact Exception object

So I have been using the ExpectedException to expect a thrown exception's types, messages, causes and even matchers.

But why isn't there a utility method to simply expect an exception object completely? Surely, I'd better off testing object equality (assuming I know what I'm doing) rather than testing all its individual attributes? After all, if a method A merely throws up any exceptions that its delegator method B throws (method A calls method B), it would be much easier for me to mock method B to throw an exception, say Exception A and check for the exact object being thrown in my method A's test method?

So why isn't such a utility method provided?

Of course I can wrap my method A call in my test and catch the exception to test the object, but the same can be said of types, messages and causes too - I'd imagine the objective is to make the test code look a lot more readable that it is w/o the try/catch block.

Upvotes: 2

Views: 672

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280138

Simply use ExpectedException#expect(Matcher) and provide a Matcher that checks reference or object equality. You can use org.hamcrest.core.Is#is(Object), passing in the exact Exception instance it will throw (if that's something you can control).

Upvotes: 5

Related Questions