Ammar
Ammar

Reputation: 4024

Alternate way to assert Exception thrown from private method in java

I need to assert that CustomException is thrown from one of the private utility method doSomething

This is what I implemented so far and is working.

Define rule at test class level

@Rule public ExpectedException exception = ExpectedException.none();

Relevant part of test method

exception.expect(CustomException.class);
// prepare call to executePrivateMethod
try {
        executePrivateMethod(objInstance, "doSomething",
                arg0, arg1);
    } catch (InvocationTargetException e) {
        Assert.assertTrue("Invalid exception thrown",
                (e.getCause() instanceof CustomException));
        throw (CustomException) e.getCause();
    }

    Assert.fail("Invalid response");


I want to know if there is / are alternate / elegant way available to achieve this?

P.S.:
1. Very helpful post but no mention of my scenario
2. executePrivateMethod uses reflection to invoke private method

Upvotes: 0

Views: 1295

Answers (1)

John B
John B

Reputation: 32979

Your design is typical for when you need to do additional verification when an exception is thrown. The only comment I would make is that you don't need the fail, exception.expect takes care of that for you.

Also, you don't need to and should not cast to a CustomException. This could result in a ClassCastException instead of the nice error message stating expected CustomException, received SomeOtherException.

Upvotes: 1

Related Questions