簡體   English   中英

當調用另一個模擬 function 時更改模擬 function 的返回值

[英]Change return value of a mock function when another mock function is called

假設我有以下模擬

enum class State
{
    IDLE,
    BUSY,
    ERROR1,
    ERROR2
};

class MockActuator : public ActuatorInterface
{
    public:
        MOCK_METHOD0(doAction, void());
        MOCK_METHOD0(getState, State());
};

我正在測試的模塊假設如果調用doAction()getState()應該返回BUSY

我如何在 GMock 下對這個假設進行編碼? 我想將getState()保留為模擬的 function,因為我需要測試其他返回值。

我的第一次嘗試如下:

    EXPECT_CALL(actuator, doAction()).Times(1).WillOnce(InvokeWithoutArgs(
                [&](){
                    ON_CALL(actuator, getState()).WillByDefault(Return(State::BUSY));
                }));

但這給出了以下神秘錯誤:

/usr/src/googletest/googlemock/include/gmock/gmock-actions.h:861:64: error: void value not ignored as it ought to be
   Result Perform(const ArgumentTuple&) { return function_impl_(); }

您可以在文檔中查看如何執行此操作的示例。

跟着你的課。

首先是模仿原件的假 class:

enum class State
{
    IDLE,
    BUSY,
    ERROR1,
    ERROR2
};

class FakeActuator : public ActuatorInterface
{
    public:
        virtual void doAction () { _state = BUSY; }
        virtual State getState () { return _state; }
    private:
        State _state;
};

之后,模擬 class:

class MockActuator : public ActuatorInterface {
 public:
  // Normal mock method definitions using gMock.
  MOCK_METHOD(void, doAction, (), (override));
  MOCK_METHOD(State, getState, (), (override));

  // Delegates the default actions of the methods to a FakeActuator object.
  // This must be called *before* the custom ON_CALL() statements.
  void DelegateToFake() {
    ON_CALL(*this, doAction).WillByDefault([this]() {
      fake_.doAction();
    });
    ON_CALL(*this, getState).WillByDefault([this]() {
      return fake_.getState();
    });
  }

 private:
  FakeActuator fake_;  // Keeps an instance of the fake in the mock.
};

就是這個“假的”object可以在通話之間保留state。 您還可以根據需要創建盡可能多的“假”類。

和測試:

TEST(AbcTest, Xyz) {
  MockFoo foo;

  foo.DelegateToFake();  // Enables the fake for delegation.

  // Put your ON_CALL(foo, ...)s here, if any.

  // No action specified, meaning to use the default action.
  EXPECT_CALL(foo, doAction());
  EXPECT_CALL(foo, getState());

  foo.doAction();  // FakeActuator::doAction() is invoked.

  EXPECT_EQ(BUSY, foo.getState());  // FakeActuator::getState() is invoked.
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM