How do I write test-only code in Production code using #ifdef in C++?

774 views Asked by At

NOTE: I think this is quite basic, please point me in the right direction if this is already answered. I did look online but surprisingly unable to find the answer, I could be using wrong words to search.

I felt I should be able to do by defining preprocessor directives in project properties but I believe I am missing something basic.

Here's what I would like to accomplish - say I have some code like the following that ships to production:

//In Foo.hpp
class Foo
{
   public:
      Foo()
      ~Foo()
      ...
}

//In Foo.cpp
Foo::Foo()
{
   #ifdef THIS_IS_TEST_MODE
      BarTest();
   #else
      Bar();
   #elseif
}

Goal: In Foo()'s constructor, I want BarTest() to run only when a Foo is instantiated in test code.

Context: I am using BOOST, so I am basically using BOOST_AUTO_TEST_SUITE and BOOST_FIXTURE_TEST_CASE macros in test code. There is a .props file that is currently included in all prod and test project files.

What I have tried already: Added another .props file with a preprocessor directive TEST and included this .props file only in test project. While #ifdef TEST evaluates to true in test project, it evaluates to false in the production code. I think this happens because the new .props config applies only to test project.

Alternatives: I guess I can add a parameter, say, bool test to Foo's ctor and default it to false so it is only true from test code. However, I feel that could lead to bugs in the future.

0

There are 0 answers