c++ - 为什么 GMOCK 对象不返回依赖注入(inject)中 EXPECT_CALL 设置的值

标签 c++ unit-testing mocking googlemock

我有以下要模拟的对象:

class Esc {
 public:
  Esc() = default;
  virtual ~Esc() {}
  virtual int GetMaxPulseDurationInMicroSeconds() const noexcept{
    return 100;
  }
};
我写了这个模拟:
class MockEsc : public Esc {
 public:
  MockEsc(){}
  MockEsc(const MockEsc&){}
  MOCK_METHOD(int, GetMaxPulseDurationInMicroSeconds, (), (const, noexcept, override));
};
这是被测单元,它调用上述 Esc.GetMaxPulseDurationInMicroSeconds()方法
class LeTodar2204{
 public:
  LeTodar2204() = delete;
  explicit LeTodar2204(std::unique_ptr<Esc> esc) : esc_(std::move(esc)){}
  int CallingMethod(){
    int a = esc_->GetMaxPulseDurationInMicroSeconds();
    return a;
  }

 private:
  std::unique_ptr<Esc> esc_;

在我的 testfixture 的 SetUp 中,我想将我的模拟设置为返回 1 并将其注入(inject)到被测单元中。
class Letodar2204Tests : public ::testing::Test {
 protected:
  Letodar2204Tests() {}
  virtual void SetUp() {
    EXPECT_CALL(esc_, GetMaxPulseDurationInMicroSeconds()).WillOnce(::testing::Return(1));
    unit_under_test_ = std::make_unique<propulsion::LeTodar2204>(std::make_unique<MockEsc>(esc_));
  }

  MockEsc esc_;
  std::unique_ptr<propulsion::LeTodar2204> unit_under_test_;
};
现在在测试中我调用了应该调用模拟方法的方法,但是 GetMaxPulseDurationInMicroSeconds我的模拟对象只返回 0(也就是默认值)并警告我有关无趣的函数调用。
这是测试
TEST_F(Letodar2204Tests, get_pulse_duration) {
  EXPECT_CALL(esc_, GetMaxPulseDurationInMicroSeconds()).WillOnce(::testing::Return(1));
  auto duration = unit_under_test_->CallingMethod();
  ASSERT_EQ(duration, 1);
}
我错过了什么?

最佳答案

因为您有效地将期望分配给您将要复制的对象。 esc_默认 ctor 将被调用一次 Letodar2204Tests被实例化。现在,在 SetUp您对类的字段 esc_ 指定期望,然后,基于 esc_创建 全新对象(在堆上,使用 make_unique )使用它的 copy-ctor。期望也不会被神奇地复制。我相信你应该存储一个 unique_ptr<MockEsc> esc_作为一个类的字段,在 SetUp 内的堆上实例化它并注入(inject)LeTodar :

class Letodar2204Tests : public ::testing::Test {
 protected:
  Letodar2204Tests() {}
  virtual void SetUp() {
    esc_ = std::make_unique<MockEsc>();
    EXPECT_CALL(*esc_, GetMaxPulseDurationInMicroSeconds()).WillOnce(::testing::Return(1));
    unit_under_test_ = std::make_unique<propulsion::LeTodar2204>(esc_);
  }

  std::unique_ptr<MockEsc> esc_;
  std::unique_ptr<propulsion::LeTodar2204> unit_under_test_;
};
在这里,您隐式调用了 copy-ctor:std::make_unique<MockEsc>(esc_)你可以做一个简单的测试:将 MockEsc 中的复制 ctor 标记为“已删除”,你会看到你的项目不再编译(至少它不应该是 :D)

关于c++ - 为什么 GMOCK 对象不返回依赖注入(inject)中 EXPECT_CALL 设置的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63520598/

相关文章:

java - Mockito 模拟所有方法调用和返回

python - 如何模拟金库 hvac.Client() 方法

c# - 如何使用最小起订量模拟 Entity Framework DbRawSqlQuery 对象?

c++ - 将 GUI C++ 应用程序转换为控制台应用程序

c++ - 将二进制转换为十六进制 : error only on 2-7

c++ - ESP8266 的单元测试框架

c# - 模拟 Entity Framework 数据库

java - 如何模拟在测试方法中创建的对象?

c++ - 将 pyqt opengl 上下文传递给 C++ 进行渲染

c++ - 从源代码构建 pcl-1.7.1 时链接到 boost 库