【问题标题】:Google Test/Mock test fail if expected call is over-saturated如果预期调用过饱和,Google 测试/模拟测试失败
【发布时间】:2011-11-28 16:24:20
【问题描述】:

如果 google mocked 方法的调用次数超过预期,如何让 google 测试失败?

示例如下:

class MockIO : iIO
{
    MOCK_METHOD1(IO_Read, void (uint8_t));
};

TEST(case, test)
{
    MockIO io;
    EXPECT_CALL(io, IO_Read(0x01)).Times(10);
    for (i=0; i<20; i++)
        io.IO_Read(0x01);
}

据我所知,我应该尝试

EXPECT_CALL(io, IO_Read(0x01)).Times(10).Throw(exception);

但在嵌入式项目中没有使用异常。

有什么想法吗?

【问题讨论】:

    标签: c++ unit-testing googletest googlemock


    【解决方案1】:

    我认为您应该在测试中使用严格的模拟。

    TEST(case, test){
    StrictMock<MockIO> io;
    EXPECT_CALL(io, IO_Read(0x01)).Times(10);
    

    使用 Strictmock 时,非预期调用会导致测试失败。

    http://code.google.com/p/googlemock/wiki/CookBook#Nice_Mocks_and_Strict_Mocks

    【讨论】:

      【解决方案2】:

      但在嵌入式项目中没有使用异常。

      没关系,因为您不应该构建单元测试以在嵌入式平台上运行,而是为您的 PC 构建。

      设置期望可以简化为:

      EXPECT_CALL(io, IO_Read(0x01)).Times( AtLeast( 10 ) );
      

      不满足条件会抛出异常。

      要让 googlemock 库在预期失败时抛出异常:

      ::testing::GTEST_FLAG(throw_on_failure) = true;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-06
        • 1970-01-01
        • 2021-12-25
        相关资源
        最近更新 更多