@Test
注释带有一个属性expectedExceptions
,您是否可以指定测试方法可能抛出的预期异常列表。
例子:
@Test(expectedExceptions = { FileNotFoundException.class, NullPointerException.class }, dataProvider = "invalidTestData" )
请注意,如果抛出的异常不是提到的列表,那么测试将被标记为失败。
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));
}
}