【问题标题】:Alternative to @Test(expected=ExceptionClass.class) for testing exceptions in testng替代 @Test(expected=ExceptionClass.class) 在 testng 中测试异常
【发布时间】: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


【解决方案1】:

我建议你看看Catch-Exception 库。它允许您对异常和任何其他相关断言执行多个断言。您可以将它与 JUnit 和 TestNG 以及您想要的任何断言框架一起使用。

示例:

@Test
public void catchExceptionTest() {
    // given: an empty list
    List<Object> myList = new ArrayList<>();

    // when: we try to get the first element of the list
    // then: catch the exception if any is thrown
    catchException(myList).get(1);

    // then: we expect an IndexOutOfBoundsException
    Exception e = caughtException();
    // Use JUnit, TestNG, AssertJ etc. assertions on the "e" exception
    assert e instanceof IndexOutOfBoundsException;
}

您可以在项目页面上找到更多示例。

【讨论】:

  • 这非常有用。我也喜欢简洁的版本verifyException(myList, IndexOutOfBoundsException.class).get(1); 虽然我仍然对 testng 开发人员没有考虑这个用例并在框架本身中对此做出任何规定感到惊讶。我将等待几天其他答案,如果我没有得到更好的答复,我会接受这个答案。
猜你喜欢
  • 1970-01-01
  • 2011-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多