JUnit4 @Test(expected=MyException.class) VS try/catch

发布于 2024-11-15 16:59:40 字数 968 浏览 1 评论 0原文

我正在考虑异常处理和单元测试最佳实践,因为我们正在尝试制定一些代码最佳实践。

在我们公司的 wiki 上找到的一篇关于最佳实践的文章指出“不要使用 try/catch,而是使用 Junit4 @Test(expect=MyException.class)”,但没有进一步的信息。我不相信。

我们的许多自定义异常都有一个枚举,以便识别失败原因。 因此,我宁愿看到像 : 这样的测试

@Test
public void testDoSomethingFailsBecauseZzz() {
try{
   doSomething();
} catch(OurCustomException e){
   assertEquals("Omg it failed, but not like we planned", FailureEnum.ZZZ, e.getFailure());
}
}

,而不是 :

@Test(expected = OurCustomException.class)
public void testDoSomethingFailsBecauseZzz() {
   doSomething();
}

当 doSomethig() 看起来像 :

public void doSomething throws OurCustomException {
  if(Aaa) {
     throw OurCustomException(FailureEnum.AAA);
  } 
  if(Zzz) {
     throw OurCustomException(FailureEnum.ZZZ);
  }
  // ...
}

时,我非常确信在某些情况下 @Test(expected=blabla.class) 是最好的选择(对于例如,当异常是精确的并且毫无疑问导致它的原因时)。

我在这里遗漏了一些东西还是应该在必要时使用 try/catch ?

I'm pondering on exception handling and unit tests best practices because we're trying to get some code best practices in place.

A previous article regarding best practices, found on our company wiki, stated "Do not use try/catch, but use Junit4 @Test(expect=MyException.class)", without further information. I'm not convinced.

Many of our custom exception have an Enum in order to identify the failure cause.
As a result, I would rather see a test like :

@Test
public void testDoSomethingFailsBecauseZzz() {
try{
   doSomething();
} catch(OurCustomException e){
   assertEquals("Omg it failed, but not like we planned", FailureEnum.ZZZ, e.getFailure());
}
}

than :

@Test(expected = OurCustomException.class)
public void testDoSomethingFailsBecauseZzz() {
   doSomething();
}

when doSomethig() looks like :

public void doSomething throws OurCustomException {
  if(Aaa) {
     throw OurCustomException(FailureEnum.AAA);
  } 
  if(Zzz) {
     throw OurCustomException(FailureEnum.ZZZ);
  }
  // ...
}

On a side note, I am more than convinced that on some cases @Test(expected=blabla.class) IS the best choice (for example when the exception is precise and there can be no doubt about what's causing it).

Am I missing something here or should I push the use of try/catch when necessary ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

远昼 2024-11-22 16:59:40

听起来您的枚举被用作异常层次结构的替代品?也许如果你有一个异常层次结构,@Test(expected=XYZ.class)会变得更有用?

It sounds like your enum is being used as an alternative to an exception hierarchy? Perhaps if you had an exception hierarchy the @Test(expected=XYZ.class) would become more useful?

清醇 2024-11-22 16:59:40
  • 如果您只想检查是否引发了某种类型的异常,请使用注释的 expected 属性。
  • 如果您想检查抛出的异常的属性(例如消息或自定义成员值),请在测试中捕获它并进行断言。

就您而言,您似乎想要后者(断言异常具有特定的 FailureEnum 值); 使用try/catch没有任何问题。

你应该“不使用 try/catch”(解释为“从不”)的概括是废话。

杰夫是对的;您的异常层次结构的组织是可疑的。不过,你似乎也认识到这一点。 :)

  • If you simply want to check that an exception of a certain type was thrown, use the annotation's expected property.
  • If you want to check properties of the thrown exception (e.g. the message, or a custom member value), catch it in the test and make assertions.

In your case, it seems like you want the latter (to assert that the exception has a certain FailureEnum value); there's nothing wrong with using the try/catch.

The generalization that you should "not use try/catch" (interpreted as "never") is bunk.

Jeff is right though; the organization of your exception hierarchy is suspect. However, you seem to recognize this. :)

西瑶 2024-11-22 16:59:40

如果您想检查原始异常类型,那么 expected 方法是合适的。否则,如果您需要测试有关异常的某些内容(并且不管测试消息内容的enum怪异情况如何),您可以执行 try catch,但这有点老派。新的 JUnit 方法是使用 MethodRule。 API 中的异常 (ExpectedException) 专门用于测试消息,但您可以轻松查看代码并调整该实现来检查失败的 enum

If you want to check the raw exception type, then the expected method is appropriate. Otherwise, if you need to test something about the exception (and regardless of the enum weirdness testing the message content is common) you can do the try catch, but that is a bit old-school. The new JUnit way to do it is with a MethodRule. The one that comes in the API (ExpectedException) is about testing the message specifically, but you can easily look at the code and adapt that implementation to check for failure enums.

岁月静好 2024-11-22 16:59:40

在您的特殊情况下,您需要测试 (1) 是否引发预期的异常 type 以及 (2) 错误号是否正确,因为该方法可能会引发不同类型的相同异常。

这需要检查异常对象。但是,您可以坚持建议验证是否引发了正确的异常:

@Test(expected = OurCustomException.class)
public void testDoSomethingFailsBecauseZzz() {
   try {
      doSomething();
   } catch (OurCustomException e) {
      if (e.getFailureEnum.equals(FailureEnum.ZZZ))  // use *your* method here
         throw e;

      fail("Catched OurCostomException with unexpected failure number: " 
        + e.getFailureEnum().getValue());  // again: your enum method here
   }
}

此模式将吃掉意外的异常并使测试失败。 Strike>

编辑

更改它是因为我错过了显而易见的事情:我们可以使测试用例失败并捕获消息。现在:如果抛出预期的异常以及预期的错误代码,则测试通过。如果测试因意外错误而失败,那么我们可以读取错误代码。

In your special case, you want to test (1) if the expected exception type is thrown and (2) if the error number is correct, because the method can thrown the same exception with different types.

This requires an inspection of the exception object. But, you can stick to the recommendation and verify that the right exception has been thrown:

@Test(expected = OurCustomException.class)
public void testDoSomethingFailsBecauseZzz() {
   try {
      doSomething();
   } catch (OurCustomException e) {
      if (e.getFailureEnum.equals(FailureEnum.ZZZ))  // use *your* method here
         throw e;

      fail("Catched OurCostomException with unexpected failure number: " 
        + e.getFailureEnum().getValue());  // again: your enum method here
   }
}

This pattern will eat the unexpected exception and make the test fail.

Edit

Changed it because I missed the obvious: we can make a test case fail and capture a message. So now: the test passes, if the expected exception with the expected error code is thrown. If the test fails because we got an unexpected error, then we can read the error code.

舟遥客 2024-11-22 16:59:40

我在搜索如何处理异常时遇到了这个。

正如 @Yishai 提到的,预期异常的首选方法是使用 JUnit 规则和 ExpectedException

使用 @Test(expected=SomeException.class) 时,如果在方法中的任何位置抛出异常,则测试方法将通过。

当您使用ExpectedException时:

@Test
public void testException()
{
    // If SomeException is thrown here, the test will fail.
    expectedException.expect(SomeException.class);
    // If SomeException is thrown here, the test will pass.
}

您还可以测试:

  • 预期消息:ExpectedException.expectMessage();
  • 预期原因:expectedException.expectCause()

附带说明:我不认为使用枚举来表示异常消息/原因是一个好的做法。 (如果我错了,请纠正我。)

I came across this when searching how to handle exceptions.

As @Yishai mentioned, the preferred way to expect exceptions is using JUnit rules and ExpectedException.

When using @Test(expected=SomeException.class) a test method will pass if the exception is thrown anywhere in the method.

When you use ExpectedException:

@Test
public void testException()
{
    // If SomeException is thrown here, the test will fail.
    expectedException.expect(SomeException.class);
    // If SomeException is thrown here, the test will pass.
}

You can also test:

  • an expected message: ExpectedException.expectMessage();
  • an expected cause: expectedException.expectCause().

As a side note: I don't think using enums for exception messages/causes is good practice. (Please correct me if I'm wrong.)

笔落惊风雨 2024-11-22 16:59:40

我做了 catch-exception 因为我遇到了和你一样的问题,Stph。
使用 catch-exception 您的代码可能如下所示:

@Test
public void testDoSomethingFailsBecauseZzz() {
   verifyException(myObj, OurCustomException.class).doSomething();
   assertEquals("Omg it failed, but not like we planned", FailureEnum.ZZZ,    
               ((OurCustomException)caughtException()).getFailure() ;
}

I made catch-exception because I was facing the same problem as you did, Stph.
With catch-exception your code could look like this:

@Test
public void testDoSomethingFailsBecauseZzz() {
   verifyException(myObj, OurCustomException.class).doSomething();
   assertEquals("Omg it failed, but not like we planned", FailureEnum.ZZZ,    
               ((OurCustomException)caughtException()).getFailure() ;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文