为什么GMOCK对象在依赖项注入中不返回EXPECT_CALL设置的值

问题描述

我有以下要模拟的对象:

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_;

在我的测试装置的设置中,我想将我的模拟设置为返回1并将其注入到被测单元中。

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_实例化后,将调用Letodar2204Tests默认ctor。现在,在SetUp中,对类的字段esc_分配期望值,然后基于esc_创建一个全新对象(在堆上,使用make_unique)使用其复制代码。期望也不会被神奇地复制。我相信您应该将unique_ptr<MockEsc> esc_作为类的字段存储,在SetUp内的堆上实例化它,然后注入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)