Uninteresting mock function call bla() && Expected: to be called at least once bla()?

前端 未结 1 1759
情话喂你
情话喂你 2020-12-20 15:31

I\'ve written a small test with a mocked class. When I run it, first I get the warning that an uninteresting mock function was called and then the test fails because the exp

相关标签:
1条回答
  • 2020-12-20 16:03

    You need to set the expectations on the actual instance of your mocked class which will be called during the test's execution.

    In your case, you're setting the expectations on the object mockBla which is only constructed then destructed at the end of the test - it is never used.

    You'll either need to pass the mock object into the CallerClass to use, or allow the CallerClass to create the mock object as a member variable, but then allow the test access to that actual member (via e.g. a getter or allowing the test to be a friend of the CallerClass).

    An example of passing the mocked object into the calling class would be something like:

    #include <memory>
    #include "gmock/gmock.h"
    
    class Bla {
     public:
      virtual ~Bla() {}
      virtual float myFunction() = 0;
    };
    
    class MockBla : public Bla {
     public:
      MOCK_METHOD0(myFunction, float());
    };
    
    class CallerClass {
     public:
      explicit CallerClass(Bla* bla) : mBla(bla) {}
      void myCallingFunction() { mBla->myFunction(); }
     private:
      Bla* mBla;
    };
    
    TEST(myTest, testMyFunction) {
      std::shared_ptr<Bla> mockBla(new MockBla);
      EXPECT_CALL(*std::static_pointer_cast<MockBla>(mockBla),
                  myFunction()).Times(testing::AtLeast(1));
    
      CallerClass callerClass(mockBla.get());
      callerClass.myCallingFunction();
    }
    
    int main(int argc, char** argv) {
      testing::InitGoogleTest(&argc, argv);
      return RUN_ALL_TESTS();
    }
    
    0 讨论(0)
提交回复
热议问题