本文介绍了如何对模板代码的故意编译错误进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请注意,这不是,因为我不关心测试外部库或编译器本身的正确性。





由于测试甚至不应该进行编译,因此您不能依靠诸如,所以我猜它应该集成到构建系统中吗?通常如何解决这些问题?

解决方案

以与编写编译器测试类似的方式进行。您将使用某种脚本语言(shell,perl,tcl等)进行一些测试代码,这些代码将在给定的代码片段上运行编译器,并检查正确的代码是否正确编译。




  • gcc使用 ,它建立在之上,后者本身是建立在Tcl之上的。

  • 如果您使用shell脚本(可能更简单,DejaGnu可能会过分杀伤),则可能需要查看。

  • Perl的 Test :: Harness 系统应该很容易使用。

  • 毕竟,从C ++运行进程并没有太多工作,因此编写一个函数以尝试在给定的字符串上调用编译器,并检查它是否在您期望不会出现的行中输出错误。很难,而且你可以理解将其示例到其他基于boost.test的测试中。


Please note that this is NOT a duplicate of How write a unit test for verifying compiling error? as I'm not concerned about testing the correctness of external libraries or the compiler itself.

It is typical in C++, particularly when dealing with templates, to employ techniques that prevent some particular piece of code from being compiled. As these can get convoluted, what is the best way to ensure that particular pieces of code do indeed generate compiler errors?

As the test shouldn't even get compiled, you can't rely on things such as boost-test, so I guess it should be integrated in the build system? How are these issues usually approached?

解决方案

Do it in the similar way compiler tests are written. You will have a bit of testing code in some scripting language (shell, perl, tcl etc.) that will run compiler on given snippets of code and check whether the right ones compiled and the right ones did not.

  • gcc uses DejaGnu, which is built on top of expect, which is itself built on top of Tcl.
  • If you use shell script (probably easier, DejaGnu is probably overkill), you might want to look at shUnit2.
  • Perl's Test::Harness system should be mostly easy to use as is.
  • After all, it's not that much more work to run process from C++, so writing a function to try to call compiler on a given string and check whether it outputs error for line where you expect it would not be that hard and than you can integrate it into the other boost.test-based tests.

这篇关于如何对模板代码的故意编译错误进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 07:25