【发布时间】:2016-02-16 11:58:12
【问题描述】:
在TestNG中,当我们想要测试一个应该抛出异常的场景时,可以编写如下代码
@Test(expected=IndexOutOfBoundsException.class, expectedExceptionsMessageRegExp="*")
public void sampleExpectedExceptionTest() {
List emptyList = new ArrayList();
// Following line should throw an IndexOutOfBoundsException
emptyList.get(0);
}
我看到有些人用以下风格编写测试。
@Test
public void sampleExpectedExceptionTest() {
// several lines here..
List emptyList = new ArrayList();
try {
emptyList.get(0);
Assert.assertFail("Expected IndexOutOfBoundsException but wasn't thrown");
} catch (IndexOutOfBoundsException e) {
// ignore
}
// ... more lines of code asserting exceptions similar to above try catch scenario
}
我不喜欢上面的风格主要是因为它非常冗长,也因为使用它的人通常在一个测试用例中编写多个测试。然而,支持它的论点是它允许用户将断言精确到特定的行,因此它更好。
最近了解了JUnit的@Rule注解
public class SampleExceptionTest {
@Rule
public final ExpectedException exception = ExpectedException.none();
@Test
public void sampleExpectedExceptionTest() {
List emptyList = new ArrayList();
exception.expect(IndexOutOfBoundsException.class);
emptyList.get(0);
}
}
这不仅允许用户将断言精确到一行,而且还阻止用户在一个测试用例中编写多个测试,因为一旦抛出异常,代码就会退出并且您无法测试多个断言。我想知道TestNG中是否有类似的选项(或成语)?我知道我可以使用预期的
【问题讨论】:
-
我希望在测试方法的最后一行抛出异常,所以我认为你的建议没有什么实际用途......
-
在测试中拥有多个断言通常是个坏主意。如果它们都失败了,你只会知道第一个断言。你应该有多个测试。
标签: java unit-testing junit testng