I am writing integration tests for my code, and the tests are data driven, different data will give back different result or throw exceptions.
@Test(dataProvider = "successTestData")
public void (String testData1, String testData2) {
//do something
}
@DataProvider
Object[][] invalidTestData() {
return new Object[][] {
{testData2, testData1}
};
}
Is it possible to add ExpectedException as part of the test data. I understand, I can add like this:
@DataProvider
Object[][] invalidTestData() {
return new Object[][] {
{testData2, testData1, expectedException}
};
}
But how do I use this in the test? I am suppose to provide the expected Exception in the annotation. Is there any way I can use it from the test data? This will help me to write a single test with different test data.
@Test
annotation comes with an attributeexpectedExceptions
, were you could specify a list of the expected exception that your test method could throw.Example:
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:
Now update the test as:
EDIT: To handle test cases that expect an exception, but exception is not thrown during actual test run.
Using
assertThrows
: