CppUnit 如何实现异常测试
我知道 CppUnit 可以通过以下方式测试异常:
CPPUNIT_ASSERT_THROW(expression, ExceptionType);
有人能解释一下 CPPUNIT_ASSERT_THROW() 是如何实现的吗?
I know that CppUnit makes it possible to test for an exception via:
CPPUNIT_ASSERT_THROW(expression, ExceptionType);
Can anybody explain how CPPUNIT_ASSERT_THROW()
is implemented?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
CppUnit 中测试失败的报告是通过抛出自定义异常类型来完成的。为了简单起见,我们在这里将其称为
CppUnitException
。CPPUNIT_ASSERT_THROW
是一个宏,它将扩展为本质上是这样的内容:如果
表达式
抛出(正如我们所期望的那样),我们就会陷入catch< /code> 块不执行任何操作。
如果
表达式
不抛出异常,则执行将继续到抛出CppUnitException
的代码行,这将触发测试失败。当然,CPPUNIT_ASSERT_THROW 宏的实现实际上有点复杂,因此还报告了行和文件信息,但这就是其工作原理的一般要点。
Reporting of test failures in CppUnit is done via throwing of a custom exception type. We'll call that
CppUnitException
here for simplicity.CPPUNIT_ASSERT_THROW
is a macro that will expand to something that is essentially this:If
expression
throws (as we'd expect it to), we fall into thecatch
block which does nothing.If
expression
does not throw, execution proceeds to the line of code that throwsCppUnitException
which will trigger a test failure.Of course, the implementation of the
CPPUNIT_ASSERT_THROW
macro is actually a bit fancier so that line and file information is also reported, but that is the general gist of how it works.编辑:我赞成 Michael Anderson 的答案,因为他对 CppUnit 的确切代码更具体,而我的答案则更笼统。
在伪代码中,它会是这样的:
Edit: I've upvoted Michael Anderson's answer, since he is more specific about the exact code from CppUnit, while mine is a more general answer.
In pseudocode, it'll be something like this: