Last Updated: February 25, 2016
·
1.035K
· gautamnitish

Expecting an exception JUnit

When expecting exceptions in the code instead of

@Test(expected=Exception.class)
public void doFooTest(){...}

do something like this

public class FooTest {
  @Rule
  public ExpectedException exception = ExpectedException.none();

  @Test
  public void doFooTest() {
    Bar bar = new Bar();

    exception.expect(IndexOutOfBoundsException.class);
    bar.doStuff();
  }
}

because the test will fail if the exception is not thrown in the second case , but in the first even if the exception is not thrown it will succeed