简体   繁体   English

单元测试未命名的命名空间中的C ++代码

[英]Unit Testing C++ Code in an Unnamed Namespace

I am working on a procedural C/C++ project. 我正在开发一个程序性的C / C ++项目。 The public interface consists of 4 functions, each with fairly complex tasks. 公共接口由4个函数组成,每个函数都有相当复杂的任务。 There are helper functions declared in the same cpp file, in an unnamed namespace. 在未命名的命名空间中,在同一个cpp文件中声明了辅助函数。 The test framework being used is GTest. 正在使用的测试框架是GTest。

However, some of these helper functions are becoming complex enough to require their own unit testing. 但是,其中一些辅助函数变得非常复杂,需要进行自己的单元测试。 Normally, I would refactor these helpers into their own testable units, but the project requirements state everything needs to be in the one cpp , and only the specified functions can be publicly visible. 通常,我会将这些帮助器重构为它们自己的可测试单元,但项目要求说明所有需要在一个cpp ,并且只有指定的函数可以公开显示。

Is there a way I can unit test the helper functions while minimizing coupling, and following the project requirements as closely as possible? 有没有一种方法可以在最小化耦合的同时对辅助功能进行单元测试,并尽可能地遵循项目要求?

A possible solution I had was to use a macro to turn the namespace into a named one for testing, and unnamed for production. 我可能的解决方案是使用宏将命名空间转换为命名的命名空间以进行测试,并为生产命名。 However, that seemed a bit messier than I would like. 然而,这似乎比我想要的更麻烦。

Both definitions and declarations in an anonymous namespace are only visible within the same translation unit. 匿名namespace中的定义和声明仅在同一个翻译单元中可见。

There are two approaches you can take to unit test these private functions. 您可以采用两种方法对这些私有函数进行单元测试。

You can #include the entire .cpp file being tested in your _test.cpp file. 您可以#include_test.cpp文件中测试的整个.cpp文件。 ( #include ing .cpp files is not a good way to reuse code - you should not do this in production code!) #include ing .cpp文件不是重用代码的好方法 - 你不应该在生产代码中这样做!)

Perhaps a better approach is to move the private code into a foo::internal namespace , where foo is the namespace your project normally uses, and put the private declarations in a -internal.h file. 也许更好的方法是将私有代码移动到foo::internal namespace ,其中foo是项目通常使用的namespace ,并将私有声明放在-internal.h文件中。 Your production .cpp files and your tests are allowed to include this internal header, but your clients are not. 您的生产.cpp文件和测试允许包含此内部标题,但您的客户端不允许。 This way, you can fully test your internal implementation without leaking it to your clients. 这样,您就可以完全测试内部实现,而不会泄漏给客户。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM