简体   繁体   English

如何在匿名命名空间中使用google test和免费功能?

[英]How to use google test with free functions in anonymous namespaces?

I have a class that does a number of things. 我有一个课,做了很多事情。 In order to split work into logical units, I've created a number of free functions in the anonymous namespace, as they're only used in this class. 为了将工作分成逻辑单元,我在匿名命名空间中创建了许多自由函数,因为它们仅在此类中使用。

I'm currently using gtest to unit test my classes. 我目前正在使用gtest来测试我的课程。 How can I implement unit tests for my anon namespace free functions? 如何为我的匿名命名空间自由函数实现单元测试?

First of all, you should not have functions in an anonymous namespace in a header. 首先,您不应该在标头中的匿名命名空间中具有函数。

That means, you want to unit test your functions in an anonymous namespace in source file. 这意味着,您希望在源文件中的匿名命名空间中对您的函数进行单元测试。

The simplest answer is : you can't and don't those functions, since they are only available to the source file (translation unit) where they are defined. 最简单的答案是:您不能也不能执行这些功能,因为它们仅适用于定义它们的源文件(翻译单元)。

However, you could call methods and functions, calling those functions, and test their outputs. 但是,您可以调用方法和函数,调用这些函数并测试它们的输出。

Another option is to move them out of anonymous namespace, and declare in the header. 另一种选择是将它们移出匿名命名空间,并在标题中声明。 Then you can use some kind of unique namespace. 然后你可以使用某种独特的命名空间。 For example : 例如 :

// header

int someFunc();

namespace hidden {
float myFunc1(int);
}

Google suggests including the .cpp file in the test. 谷歌建议在测试中加入.cpp文件。 I think it's a small price to pay to keep my source code clean. 我认为保持源代码清洁是一个很小的代价。

No one can access your function in anonymous namespace out of .cpp, so if you really need to test your function, put these functions a subtle namespace or something like that. 没有人可以在.cpp之外的匿名命名空间中访问你的函数,所以如果你真的需要测试你的函数,那么把这些函数放在一个微妙的命名空间或类似的东西。 reference implement in chrome chrome中的参考工具

namespace xxx {
namespace subtle {
   your help functions..
}
}

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

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