CppUnit 如何实现异常测试

发布于 2024-08-29 14:29:01 字数 155 浏览 4 评论 0原文

我知道 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 技术交流群。

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

发布评论

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

评论(2

苏佲洛 2024-09-05 14:29:01

CppUnit 中测试失败的报告是通过抛出自定义异常类型来完成的。为了简单起见,我们在这里将其称为 CppUnitException

CPPUNIT_ASSERT_THROW 是一个宏,它将扩展为本质上是这样的内容:

try
{
   expression;
   throw CppUnitException("Expected expression to throw");
}
catch( const ExceptionType & e )
{
}

如果表达式抛出(正如我们所期望的那样),我们就会陷入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:

try
{
   expression;
   throw CppUnitException("Expected expression to throw");
}
catch( const ExceptionType & e )
{
}

If expression throws (as we'd expect it to), we fall into the catch block which does nothing.

If expression does not throw, execution proceeds to the line of code that throws CppUnitException 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.

披肩女神 2024-09-05 14:29:01

编辑:我赞成 Michael Anderson 的答案,因为他对 CppUnit 的确切代码更具体,而我的答案则更笼统。

在伪代码中,它会是这样的:

try
  {
  // Test code that should throw      
  }
catch(ExceptionType e)
  {
  // Correct exception - handle test success
  return; 
  }
catch(...)
  {
  // Wrong exception, handle test failure.
  return;
  }
// No exception, handle test failure.
return;

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:

try
  {
  // Test code that should throw      
  }
catch(ExceptionType e)
  {
  // Correct exception - handle test success
  return; 
  }
catch(...)
  {
  // Wrong exception, handle test failure.
  return;
  }
// No exception, handle test failure.
return;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文