C ++, Googlemock - testing a local object

I started using the googletest and googlemock libraries, and I have a problem that I cannot solve. I have a code something like this:

class Painter { public: void DrawSomething(); }; void Painter::DrawSomething() { Turtle turtle; turtle.doSomething(); } main() { Painter p; p.DrawSomething(); } 

I mocked the Turtle class, but how can I test the doSomething () method (e.g. with EXPECT_CALL) when the turtle object is created locally? Is this possible without changing the Painter class?

Thanks for answers.

+5
source share
1 answer

I mocked the Turtle class ...

How exactly did you mock this?

... but how can I test the doSomething() method (e.g. with EXPECT_CALL ) when the turtle object is created locally? Is this possible without changing the Painter class?
(Emphasis mine)

Direct answer: None .

You cannot magically enter a layout instead of the real instance used in another class, without decoupling through the interface.


Instead, you should have something like the following code:

 struct ITurtle { virtual void PenUp() = 0; virtual void PenDown() = 0; virtual void TurnLeft(double degrees) = 0; virtual void Move(double distance) = 0; // ... virtual ~ITurtle() {} }; 

 struct TurtleMock : ITurtle { // Mock method declarations MOCK_METHOD0(PenUp, void ()); MOCK_METHOD0(PenDown, void ()); MOCK_METHOD1(TurnLeft, void (double)); MOCK_METHOD1(Move, void (double)); }; 

 class Turtle : public ITurtle { public: void PenUp(); void PenDown(); void TurnLeft(double degrees); void Move(double distance); }; 

Ensure the real implementation of the above declarations in a separate translation unit.


 class Painter { public: Painter(ITurtle& turtle) : turtle_(turtle) {} void DrawSomething(); private: ITurtle& turtle_; }; void Painter::DrawSomething() { turtle_.PenDown(); turtle_.TurnLeft(30.0); turtle_.Move(10.0); turtle_.TurnLeft(30.0); turtle_.Move(10.0); // ... } 

You can alternatively pass the ITurtle interface ITurtle the DrawSomething() function:

 class Painter { public: void DrawSomething(ITurtle& turtle); }; void Painter::DrawSomething(ITurtle& turtle) { turtle.PenDown(); turtle.TurnLeft(30.0); turtle.Move(10.0); turtle.TurnLeft(30.0); turtle.Move(10.0); // ... } 

 int main() { NiceMock<TurtleMock> turtle; Painter p(turtle); // Painter p; <<< for the alternative solution EXPECT_CALL(turtle,PenDown()) .Times(1); EXPECT_CALL(turtle,TurnLeft(_)) .Times(2); EXPECT_CALL(turtle,Move(_)) .Times(2); p.DrawSomething(); // p.DrawSomething(turtle); <<< for the alternative solution } 
+3
source

All Articles