I would use an auxiliary method and do it this way:
EDIT: This does not work, see alternative working solution
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void myTest() {
List<Object[]> paramsList = Arrays.asList(
new Object[] {"", IllegalArgumentException.class},
new Object[] {null, NullPointerException.class});
paramsList.forEach(a -> assertExceptionForParam((String)a[0], (Class)a[1]));
}
private void assertExceptionForParam(String param, Class expectedExceptionClass) {
thrown.expect(expectedExceptionClass);
testedObject.supposedToFail(param);
}
ALTERNATIVE WORKING SOLUTION, CHANGE AFTER COMMENT BY MIRZAK
My solution seems to actually only test the first case in the list. Here is a working version that will test them all
@Test
public void myTest() {
List<Object[]> paramsList = Arrays.asList(
new Object[] {null, NullPointerException.class},
new Object[] {"", IllegalArgumentException.class},
new Object[] {"zip", NullPointerException.class});
paramsList.forEach(a -> assertExceptionForParam((String)a[0], (Class)a[1]));
}
private void assertExceptionForParam(String param, Class expectedExceptionClass) {
boolean pass = false;
try {
testedObject.supposedToFail(param);
} catch(Exception e) {
pass = e.getClass() == expectedExceptionClass;
}
Assert.assertTrue("test failed for param:" + param + " and Exception "+expectedExceptionClass, pass);
}
This outputs, as expected:
java.lang.AssertionError: test failed for param:zip and Exception class java.lang.NullPointerException