简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM