4

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();
    }
}
Punter Vicky
  • 15,954
  • 56
  • 188
  • 315

2 Answers2

4

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)

Dangermouse
  • 290
  • 1
  • 3
  • 11
  • Thank You!! I had placed exception.expect(IllegalArgumentException.class); below toTest() and realize the folly now! – Punter Vicky Sep 27 '16 at 16:35
1

An alternative approach (and simpler?) to using a Rule is to place a fail() after the call where you expect the exception to occur. If you get the exception, the test method succeeds (you never reach the fail). If you don't get the exception and you reach the fail() statement, then the test fails.

Kevin Hooke
  • 2,583
  • 2
  • 19
  • 33