@Test
annotation comes with an attribute expectedExceptions
, were you could specify a list of the expected exception that your test method could throw.
Example:
@Test(expectedExceptions = { FileNotFoundException.class, NullPointerException.class }, dataProvider = "invalidTestData" )
Note that, if the exception thrown is not is the mentioned list, then the test would be marked as failed.
So using this, there is no need to pass the exception as part of the dataProvider.
EDIT: If each of the test data throws a different exception, then you could pass it using dataProvider as below:
@DataProvider
Object[][] invalidTestData() {
return new Object[][] {
{testData1, NullPointerException.class},
{testData2, FileNotFoundException.class}
};
}
Now update the test as:
@Test(dataProvider = "invalidTestData")
public void (String testData, Class<? extends Exception> exceptionType) {
try {
// do something with testData
} catch (Exception e) {
Assert.assertEquals(e.getClass, exceptionType);
}
}
EDIT: To handle test cases that expect an exception, but exception is not thrown during actual test run.
@Test(dataProvider = "invalidTestData")
public void (String testData, Class<? extends Exception> exceptionType) {
try {
// do something with testData which could possibly throw an exception.
// code reaches here only if no exception was thrown
// So test should fail if exception was expected.
Assert.assertTrue(exceptionType == null);
} catch (Exception e) {
Assert.assertEquals(e.getClass, exceptionType);
}
}
Using assertThrows
:
@Test(dataProvider = "invalidTestData")
public void (String testData, Class<? extends Exception> exceptionType) {
if (exceptionType == null) {
someMethod(testData);
} else {
Assert.assertThrows(exceptionType, someMethod(testData));
}
}