Punter Vicky Punter Vicky - 2 months ago 10
Java Question

JUNIT - Asserting Exceptions

I am using JUNIT 4. I tried to assert the exception using the below code , but it did not work.

@Rule
public ExpectedException thrown = ExpectedException.none();
thrown.expect(ApplicationException.class);


However when I annotated using the below , it worked and test passed.

@Test(expected=ApplicationException.class)


Please let me know if I am missing something.

import org.junit.Rule;
import org.junit.rules.ExpectedException;

public class Test
{

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

@org.junit.Test
public void throwsIllegalArgumentExceptionIfIconIsNull()
{


exception.expect(IllegalArgumentException.class);
toTest();
}

private void toTest()
{
throw new IllegalArgumentException();
}
}

Answer

The following code is a minimal example of using the exception rule.

public class Test
{

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

    @org.junit.Test
    public void throwsIllegalArgumentExceptionIfIconIsNull()
    {
        exception.expect(IllegalArgumentException.class);
        toTest();
    }

    private void toTest()
    {
        throw new IllegalArgumentException();
    }
}

Please see also (Wiki entry about rules)

Comments