如何测试是否未抛出特定异常?

如何测试是否未抛出特定异常?

问题描述:

我可以测试是否抛出特定异常?

Can I test whether a particular Exception is not thrown?

相反,使用@Test[expect=MyException]很容易.

但是我该如何否定呢?

如果要测试是否在 other 异常可能发生的情况下抛出了 not 异常,被扔,试试这个:

If you want to test if a particular Exception is not thrown in a condition where other exceptions could be thrown, try this:

try {
  myMethod();
}
catch (ExceptionNotToThrow entt){
  fail("WHOOPS! Threw ExceptionNotToThrow" + entt.toString);
}
catch (Throwable t){
  //do nothing since other exceptions are OK
}
assertTrue(somethingElse);
//done!