在Google测试中使用EXPECT_NO_THROW是否有好处?

huangapple go评论95阅读模式
英文:

Is there a benefit of using EXPECT_NO_THROW in Google test?

问题

在gtest中,可以使用EXPECT_NO_THROW宏来验证一个操作是否不会引发异常。

当代码引发异常时,测试用例将标记为失败。
然而,如果未使用EXPECT_NO_THROW宏并引发异常,测试用例也会失败。

据我观察,以下两种方式在功能上是等效的:

sut.do_action();
EXPECT_NO_THROW(sut.do_action());

那么,是否有使用EXPECT_NO_THROW的好处或原因?还是它的唯一目的是使测试用例规范更明确?

英文:

In gtest one can use the EXPECT_NO_THROW macro to verify that an action does not throw an exception.

When the code does thrown an exception, the test case will be marked as failed.
However, if the EXPECT_NO_THROW macro is not used and an exception is thrown, the test case will fail too.

As far as I can observe the following are functionally equivalent:
<!-- language-all: C++ -->

sut.do_action();
EXPECT_NO_THROW(sut.do_action());

So, is there any benefit or reason to use EXPECT_NO_THROW? Or is its only purpose to make the test case specification more explicit?

答案1

得分: 2

  1. 它使您能够在异常抛出时输出某些内容
    EXPECT_NO_THROW(sut.do_action()) &lt;&lt; "必须不抛出异常";
  2. 它允许测试用例在异常抛出后继续执行
    std::cout &lt;&lt; "继续\n";  // 不会输出
    
    std::cout &lt;&lt; "继续\n";  // 无论是否抛出异常都会输出
    
英文:

It's so obvious.

  1. It gives you ability to output something if an exception thrown
    EXPECT_NO_THROW(sut.do_action()) &lt;&lt; &quot;Must not throw&quot;;
    
  2. It allows a test case to continue after an exception is thrown
    sut.do_action();
    std::cout &lt;&lt; &quot;Continue\n&quot;;  // does not output
    
    EXPECT_NO_THROW(sut.do_action());
    std::cout &lt;&lt; &quot;Continue\n&quot;;  // outputs regardless of an exception
    

huangapple
  • 本文由 发表于 2023年6月1日 16:03:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76379847.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定