1

我正在为我的代码编写集成测试,测试是数据驱动的,不同的数据会返回不同的结果或抛出异常。

@Test(dataProvider = "successTestData")
public void (String testData1, String testData2) {
    //do something
}

@DataProvider
Object[][] invalidTestData() {
    return new Object[][] {
        {testData2, testData1}
    };
}

是否可以将 ExpectedException 添加为测试数据的一部分。我明白了,我可以这样添加:

@DataProvider
Object[][] invalidTestData() {
    return new Object[][] {
        {testData2, testData1, expectedException}
    };
}

但是我如何在测试中使用它呢?我想在注释中提供预期的异常。有什么方法可以从测试数据中使用它吗?这将帮助我用不同的测试数据编写一个测试。

4

1 回答 1

0

@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));
    }
}
于 2021-05-05T16:32:15.457 回答