【问题标题】:gtest - ensure that a method is not called before, but can be called after a certain method callgtest - 确保一个方法之前没有被调用,但可以在某个方法调用之后被调用
【发布时间】:2019-04-16 15:28:27
【问题描述】:

如何测试setState() 方法在subscribe() 之前没有被调用,同时允许但不强制在之后调用它?

下面的代码显示了我想要实现的目标。

这是我要测试的方法:

...

void FirstState::enter()
{
    mInfoSubscription.subscribe(mInfoListener);

    mStateMachine.setState(mFactory.makeState(StateId::SecondState));
}

...

这是一个单元测试:

class FirstStateTest : public ::testing::Test {
protected:
    FirstStateTest()
        : mFirstState{mMockStateMachine, mMockStatesFactory,
                      mMockInfoSubscription, mMockInfoListener}
    {
    }

    NiceMock<MockStateMachine> mMockStateMachine;
    NiceMock<MockStatesFactory> mMockStatesFactory;
    NiceMock<MockInfoSubscription> mMockInfoSubscription;
    NiceMock<MockInfoListener> mMockInfoListener;

    FirstState mFirstState;
};

TEST_F(FirstStateTest, ensure_that_subscription_is_done_before_state_change)
{
    // This method must not be called before "subscribe()".
    EXPECT_CALL(mMockStateMachine, doSetState(_)).Times(0);  // doesn't work the way I want

    EXPECT_CALL(mMockInfoSubscription, subscribe(_)).Times(1);

    // At this moment it doesn't matter if this method is called or not.
    EXPECT_CALL(mMockStateMachine, doSetState(_)).Times(AtLeast(0));  // doesn't work the way I want

    mFirstState.enter();
}

// other unit tests ...
...

编辑 1:

以防万一,MockStateMachine 的外观如下:

class MockStateMachine : public IStateMachine {
public:
    MOCK_METHOD1(doSetState, void(IState* newState));
    void setState(std::unique_ptr<IState> newState) { doSetState(newState.get()); }
};

【问题讨论】:

    标签: c++ unit-testing googletest gmock


    【解决方案1】:

    您可以使用::testing::InSequence 来确保预期的呼叫是有序的。

    TEST_F(FirstStateTest, ensure_that_subscription_is_done_before_state_change) {
      InSequence expect_calls_in_order;
    
      // `subscribe` must be called first.
      EXPECT_CALL(mMockInfoSubscription, subscribe(_)).Times(1);
    
      // After the `subscribe` call, expect any number of SetState calls.
      EXPECT_CALL(mMockStateMachine, doSetState(_)).Times(AtLeast(0));
    
      mFirstState.enter();
    }
    

    【讨论】:

    猜你喜欢
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-30
    • 1970-01-01
    相关资源
    最近更新 更多