How to use gmock to verify that a class calls base class methods

class Foo { public: int x; int y; void move(void); }; class SuperFoo: public Foo { public: int age; void update(); }; SuperFoo::update(void) { move(); age++; } 

I'm just starting out with C ++ and unit testing, I have code similar to the above, and I want to use gmock to verify that SuperFoo::update() calls the base class move() method. What would be the best way to attack this type of situation?

+5
source share
1 answer

One way - to make the method move virtual and create a layout of your class:

 #include "gtest/gtest.h" #include "gmock/gmock.h" class Foo { public: int x; int y; virtual void move(void); //^^^^ following works for virtual methods }; // ... class TestableSuperFoo : public SuperFoo { public: TestableSuperFoo(); MOCK_METHOD0(move, void ()); void doMove() { SuperFoo::move(); } }; 

Then, in your test, configure the appropriate call waiting

 TEST(SuperFoo, TestUpdate) { TestableSuperFoo instance; // Setup expectations: // 1) number of times (Times(AtLeast(1)), or Times(1), or ... // 2) behavior: calling base class "move" (not just mock's) if "move" // has side-effects required by "update" EXPECT_CALL(instance, move()).Times(testing::AtLeast(1)) .WillRepeatedly(testing::InvokeWithoutArgs(&instance, &TestableSuperFoo::doMove)); const int someValue = 42; instance.age = someValue; // Act instance.update(); // Assert EXPECT_EQ(someValue+1, instance.age); } 
+4
source

Source: https://habr.com/ru/post/1201078/


All Articles