Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if Google Test is running in my code

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?

like image 944
MahlerFive Avatar asked May 20 '11 21:05

MahlerFive


People also ask

How do I add a Google Test to Visual Studio code?

Add a Google Test project in Visual Studio 2022In Solution Explorer, right-click on the solution node and choose Add > New Project. Set Language to C++ and type test in the search box. From the results list, choose Google Test Project. Give the test project a name and choose OK.

How do I skip a Google Test?

If you have a broken test that you cannot fix right away, you can add the DISABLED_ prefix to its name. This will exclude it from execution. This is better than commenting out the code or using #if 0 , as disabled tests are still compiled (and thus won't rot).


1 Answers

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.

like image 114
Rob Kennedy Avatar answered Nov 15 '22 08:11

Rob Kennedy