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;
struct TurtleMock : ITurtle {
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);
source share