user1228352
user1228352

Reputation: 569

Mocking member functions while unit testing C++ class gtest/gmock

I have a following class (This is a very simplified version of actual class.)

class PostCalc
{
public:
    virtual int add(int a, int b) { return a+b; } // Actual function is complex
    virtual int multiply(int a, int b) { return a*b; } // So this one
    virtual int multiop(int a, int b) { return add(a, b) + multiply(a, b); } 
};

For example, If I want to do unit test of multiop() and mock other member functions [ add() and multiply() ], how we can achieve so? I am thinking to create mock class of PostCalc, gmocked add() and multiply() and created a delegate function for multiop().

  class PostCalcMock : public PostCalc                            
  {                                                                               
  public:                                                                            
      MOCK_METHOD2(add, int(int a, int b)); 
      MOCK_METHOD2(multiply, int(int a, int b));       

      // Delegate                                                            
      int delegateToMultiOp(int a, int b) { 
          return multiop(a, b);
      }                                                                           
  };

Is this a good way to handle? Any help is appreciated.

Thanks in advance.

Upvotes: 0

Views: 2293

Answers (1)

Elvis Oric
Elvis Oric

Reputation: 1364

You do not need delegateToMultiOp. Always focus to test your desired public behavior. I can see here that your intention is, whenever someone calls multiop, the result is that add and multiply will be called.

namespace {
class PostCalc {
  public:
  virtual int add(int a, int b) { return a + b; }  // Actual function is complex
  virtual int multiply(int a, int b) { return a * b; }  // So this one
  virtual int multiop(int a, int b) { return add(a, b) + multiply(a, b); }
};

class PostCalcMock : public PostCalc {
  public:
  MOCK_METHOD2(add, int(int a, int b));
  MOCK_METHOD2(multiply, int(int a, int b));
};
struct MultipleOperationsTest : public testing::Test {};
}  // namespace

TEST_F(MultipleOperationsTest, ExpectsToConfirmThatAddAndMultiplyIsCalled) {
  PostCalcMock mock;
  int a = 2, b = 3;
  EXPECT_CALL(mock, add(a, b));
  EXPECT_CALL(mock, multiply(a, b));
  mock.multiop(a, b);
}

Upvotes: 1

Related Questions