首页 > 解决方案 > 在 GoogleMock 的循环中期望两个方法调用中的任何一个

问题描述

我有一个Foo引用多个其他类型对象的类IBar。该类有一个方法fun需要调用frob1()frob2()基于数字。我想用 mocked 编写一个测试IBars来验证这个要求。我正在使用 GoogleMock。我目前有这个:

class IBar 
{ 
public: 
    virtual void frob1() = 0; 
    virtual void frob2() = 0; 
};
class MockBar : public IBar 
{ 
public: 
    MOCK_METHOD0(frob1, void ()); 
    MOCK_METHOD0(frob2, void ()); 
};

class Foo {
    std::shared_ptr<IBar> bar;
public:
    Foo(std::shared_ptr<IBar> bar)
        : bar(std::move(bar))
    {}
    void fun(int num) {
        for (int n = 1; n <= num; ++n) {
            if (n % 2 == 0) bar->frob1();
            else bar->frob2();
        }
    }
};

TEST(FooTest, callsAtLeastOneFrob) {
    auto bar = std::make_shared<MockBar>();
    Foo foo(bar);

    // HOW TO WRITE THE FOLLOWING EXPECT_CALL IN A LOOP?
    EXPECT_CALL(*bar, frob1()).Times(5);
    EXPECT_CALL(*bar, frob2()).Times(5);

    foo.fun(10);
}

编辑: 这是我尝试过的:

MockFunction<void()> check_point;
for (int count = 1; count <= 10; ++count) {
    EXPECT_CALL(*bar, frob1())
        .WillOnce(InvokeWithoutArgs(&check_point, &MockFunction<void()>::Call));
    EXPECT_CALL(*bar, frob2())
        .WillOnce(InvokeWithoutArgs(&check_point, &MockFunction<void()>::Call));
    EXPECT_CALL(check_point, Call())
        .Times(1);
}

当我运行时,我看到以下错误:

Expected: the expectation is active
Actual: it is retired
Expected: to be called any number of times
Actual: never called - satisfied and retired

我正在尝试循环模拟该函数。如何EXPECT_CALL循环写入?

标签: c++unit-testingmockinggoogletestgooglemock

解决方案


推荐阅读