Arnab
Arnab

Reputation: 195

Test a method which throws an exception using Junit

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

Answers (2)

Jellis Torfs
Jellis Torfs

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

Stefan Birkner
Stefan Birkner

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

Related Questions