其他分享
首页 > 其他分享> > c – 无趣的模拟函数调用bla()\u0026\u0026预期:至少调用一次bla()?

c – 无趣的模拟函数调用bla()\u0026\u0026预期:至少调用一次bla()?

作者:互联网

我用模拟课写了一个小测试.当我运行它时,首先我得到一个警告,即调用了一个无趣的模拟函数,然后测试失败,因为没有满足期望,即模拟函数被调用至少一次.有趣的是,当我看到上面的警告信息时,调用该函数.

你对这件事有什么看法吗?

谢谢!

编辑:这是我的代码结构:

class Bla {

public:
    Bla();
    virtual ~Bla();

    virtual float myFunction();
}

class MockBla : public Bla {
    MockBla();
    ~MockBla();
    MOCKMETHOD0(myFunction, float());
}

class CallerClass {

public:
    CallerClass() { MockBla* myMock = new MockBla(); }
    virtual ~CallerClass();

    myCallingFunction() { myMock->myFunction(); }
}

class MyTestClass : public ::testing::Test {
//....
    TEST(myTest, testMyFunction) {
    MockBla mockBla;
    EXPECT_CALL(mockBla, myFunction()).Times(AtLeast(1));

    CallerClass* callerClass;
    callerClass = new CallerClass();

    callerClass->myCallingFunction();

    }
//....
}

结果:

[ RUN      ] MyTestClass.testMyFunction

GMOCK WARNING:
Uninteresting mock function call - returning default value.
    Function call: myFunction()
          Returns: 0
Stack trace:
MyTestClass.cpp:99: Failure
Actual function call count doesn't match EXPECT_CALL(mockBla, myFunction())...
         Expected: to be called at least once
           Actual: never called - unsatisfied and active

解决方法:

您需要在测试执行期间调用的模拟类的实际实例上设置期望值.

在您的情况下,您正在设置对象mockBla的期望,该对象仅在测试结束时被构造然后被破坏 – 它从未被使用过.

您需要将模拟对象传递给CallerClass以使用,或者允许CallerClass将模拟对象创建为成员变量,但允许对该实际成员的测试访问(通过例如getter或允许测试到成为CallerClass的朋友.

将模拟对象传递给调用类的示例如下:

#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();
}

标签:c,mocking,googletest,googlemock
来源: https://codeday.me/bug/20190723/1509428.html