如何检查Google Test是否正在我的代码中运行 [英] How to check if Google Test is running in my code

查看:132
本文介绍了如何检查Google Test是否正在我的代码中运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果要进行单元测试,我有一段代码不希望运行.我希望找到一些我可以检查的gtest库设置的#defined标志.我找不到用于该目的的应用程序,但是在浏览了gtest标头之后,我发现了一个我可以使用的示例:

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?

推荐答案

Google测试不需要或提供自己的构建包装器.您甚至不必有时重新编译源文件.您可以将它们与您的测试代码链接在一起.您的测试代码将调用您已经编译的库代码.您的库代码可能甚至不包含和Gtest标头.

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.

如果您希望您的库代码在测试中以不同的方式运行,那么首先需要确保您的库代码在测试中以不同的方式编译.您将需要另一个构建目标.为该构建目标进行编译时,可以定义一个符号,向您的代码指示其处于测试模式.我会避免使用该符号的GTEST前缀;留给Google自己的代码使用.

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.

实现您正在寻找的另一种方法是使用依赖注入.将您的特殊代码移动到另一个例程中,可能在其自己的类中.将指向该函数或类的指针传递到您的SomeFunctionImUnitTesting函数中,然后调用它.在测试该代码时,可以使测试工具向该代码传递不同的函数或类,从而避免了有问题的代码,而无需多次编译代码.

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.

这篇关于如何检查Google Test是否正在我的代码中运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆