Reputation: 195
I am trying to write a test case for a method which throws an exception based on certain logic. However the test case fails as the expected exception and obtained exceptions are different.
Method to test -
public void methodA (//parameters) throws ExceptionA
{
certainlogic=//call some method
if (certainlogic)
throw new ExceptionA(//exception details)
else
//code snippet
}
Test method -
@Test (expected=ExceptionA.class)
public void testMethodA
{
try
{
when (//mock method).thenReturn(true);
//call methodA
}
catch (ExceptionA e)
{
fail(e.printStackTrace(e));
}
}
I am receiving the below error -
Unexpected exception, expected<cExceptionA> but was<java.lang.AssertionError>
How do I solve this issue?
Upvotes: 1
Views: 2897
Reputation: 51
You should remove the try-catch block entirely or at least the catch. The "expected = ExceptionA.class" tells junit to monitor for thrown exceptions, catch them and compare their class against the given class. If you catch the thrown exception, the @Test-annotated junit method cannot detect if such an exception is thrown. By calling fail(...) you implicitly throw an AssertionError which junit detects and thus your test fails because AssertionError.class != ExceptionA.class
Upvotes: 0
Reputation: 24550
You have to remove the catch
in your test
@Test (expected=ExceptionA.class)
public void testMethod()
{
when (//mock method).thenReturn(true);
//call methodA
}
Otherwise you catch the ExceptionA
and by calling fail
you throw an AssertionError. Obviously the AssertionError
is not an ExceptionA
and therefore your test fails.
Upvotes: 3