It depends on the JUnit version and what assert libraries you use.
- For JUnit5 and 4.13 see answer https://stackoverflow.com/a/2935935/2986984
- If you use assertJ or google-truth, see answer https://stackoverflow.com/a/41019785/2986984
The original answer for JUnit <= 4.12
was:
@Test(expected = IndexOutOfBoundsException.class)
public void testIndexOutOfBoundsException() {
ArrayList emptyList = new ArrayList();
Object o = emptyList.get(0);
}
Though answer https://stackoverflow.com/a/31826781/2986984 has more options for JUnit <= 4.12.
Reference :
- JUnit Test-FAQ