Search code examples
c++unit-testingc++11googletestgooglemock

How to Skip a Portion of the ”Code” in the source code while doing GoogleTest


I tried using a debug flag addition (GOOGLE_TEST) in the source code and defined it in the TEST/Makefile.am. but the things didn’t work. I am using C++ Language. Note: I don’t want to change anything in the SRC Directory code which will affect the production code and its Makefile.am

Test Class in SRC Directory

class Common: public Thread {
 public:
  friend class test_common;
  Common {
  }
  ~Common () {
  }
  virtual void ThreadMain();
 protected:
  virtual void ProcessData(void);
};
void Common::ProcessData(void) {
  #ifndef __GOOGLE_TEST__
  while (1) { }
  #endif
}

TESTCODE in test Directory

class test_common : public ::testing::Test {
};
TEST_F(test_common, create_common) {
    Common commonObj();
    commonObj. ProcessData ();
}

OUTPUT

GTest Stuck in the While loop part even after defining the flag in the test/makefile.am


Solution

  • Dont rely on the compilation flags, without affecting the production code use the GMOCK methods to get rid off the while (1) loop , the code can go like below:

    TESTCODE:

    class test_common : public ::testing::Test {
    };
    TEST_F(test_common, create_common) {
        Common commonObj();
        ON_CALL(mock_if, GetBool())
          .WillByDefault(Return(true));
        EXPECT_CALL(mock_if, GetBool())
          .Times(AtLeast(1))
          .WillOnce(Return(true))
          .WillOnce(Return(false));
        commonObj. ProcessData ();
    }
    

    ABSTRACT CODE:

    class AbstractIf {
     public:
      AbstractIf (void) = default;
      virtual ~AbstractIf (void) = default;
      virtual bool GetBool() = 0;
    };
    

    MOCK CODE:

    class MockIf : public AbstractIf {
      public:
        MOCK_METHOD0(GetBool,bool());
    };
    

    SOURCE CODE:

    class Common: public Thread {
     public:
      friend class test_common;
      Common {
      }
      ~Common () {
      }
      virtual void ThreadMain();
     protected:
      virtual void ProcessData(void);
      AbstractIf *prov_fl_if_;
    };
    void Common::ProcessData(void) {
      while (prov_fl_if_->GetBool())  { }
    }
    

    By this way we can skip the part of the code we want without affecting the production code