如何检查 Google Test 是否在我的代码中运行
我有一段代码,如果正在进行单元测试,我不想运行它。我希望找到一些由 gtest 库设置的 #define 标志,我可以检查。我找不到用于此目的的一个,但在查看 gtest 标头后,我发现了一个我认为可以像这样使用的:
SomeClass::SomeFunctionImUnitTesting() {
// some code here
#ifndef GTEST_NAME
// some code I don't want to be tested here
#endif
// more code here
}
这似乎不起作用,因为无论如何,所有代码都会运行。我可以检查另一个可能有效的标志吗?
I have a section of code that I would not like to run if it is being unit tested. I was hoping to find some #defined flag that is set by the gtest library that I can check. I couldn't find one that is used for that purpose, but after looking through the gtest header, I found one I thought I could use like this:
SomeClass::SomeFunctionImUnitTesting() {
// some code here
#ifndef GTEST_NAME
// some code I don't want to be tested here
#endif
// more code here
}
This doesn't seem to work as all the code runs regardless. Is there another flag I can check that might work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Google Test 不需要或提供自己的构建包装器。有时您甚至不必重新编译源文件。您只需将它们与您的测试代码链接起来即可。您的测试代码调用已编译的库代码。您的库代码可能甚至不包含 Gtest 标头。
如果您希望您的库代码在测试下以不同的方式运行,那么您首先需要确保您的库代码在测试下编译不同。您将需要另一个构建目标。在针对该构建目标进行编译时,您可以定义一个符号来指示您的代码处于测试模式。我会避免使用该符号的
GTEST
前缀;留给Google自己的代码使用。实现您想要的目标的另一种方法是使用依赖注入。将您的特殊代码移动到另一个例程中,可能在它自己的类中。将指向该函数或类的指针传递到您的
SomeFunctionImUnitTesting
函数并调用它。当您测试该代码时,您可以让测试工具将不同的函数或类传递给该代码,从而避免出现有问题的代码,而无需多次编译代码。Google Test doesn't need or provide its own build wrapper. You don't even have to recompile your source files sometimes. You can just link them along with your test code. Your test code calls your already-compiled library code. Your library code probably doesn't even include and Gtest headers.
If you want your library code to run differently under test, then you first need to make sure that your library code is compiled differently under test. You'll need another build target. When compiling for that build target, you can define a symbol that indicates to your code that it's in test mode. I'd avoid the
GTEST
prefix for that symbol; leave for use by Google's own code.Another way to achieve what you're looking for is to use dependency injection. Move your special code into another routine, possibly in its own class. Pass a pointer to that function or class into your
SomeFunctionImUnitTesting
function and call it. When you're testing that code, you can have your test harness pass a different function or class to that code, therefore avoiding the problematic code without having to compile your code multiple times.在
main()
中:其他地方:
In
main()
:Somewhere else: