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?
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With