英文:
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
- 它使您能够在异常抛出时输出某些内容
EXPECT_NO_THROW(sut.do_action()) << "必须不抛出异常";
- 它允许测试用例在异常抛出后继续执行
std::cout << "继续\n"; // 不会输出
std::cout << "继续\n"; // 无论是否抛出异常都会输出
英文:
It's so obvious.
- It gives you ability to output something if an exception thrown
EXPECT_NO_THROW(sut.do_action()) << "Must not throw";
- It allows a test case to continue after an exception is thrown
sut.do_action(); std::cout << "Continue\n"; // does not output
EXPECT_NO_THROW(sut.do_action()); std::cout << "Continue\n"; // outputs regardless of an exception
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论