【问题标题】:How to mock method with pointer argument如何使用指针参数模拟方法
【发布时间】:2014-08-03 15:32:56
【问题描述】:

是否可以模拟检索指针(或引用)作为参数并更改指向对象的方法?

我使用海龟库 - http://turtle.sourceforge.net/ -> 用于 Boost 的 C++ 模拟对象库。 (我知道它不是流行的库,但在其他库中可能类似)。

例如:我需要将方法模拟为:

int f(int* x)
{
    *x = new_value;
    return 0;
}

下一个 SUT 在代码中使用 x 值:(

我可以设置我的模拟返回什么。但是修改参数呢?

怎么做?

【问题讨论】:

  • *x = new_value;替换// *x is modified (object pointed by x is modified)
  • 这是 SUT(被测系统)中的方法。我需要在我的测试中模拟这种方法的行为(在预期中)。

标签: c++ unit-testing boost mocking turtle-mock


【解决方案1】:

看看调用和返回动作: http://turtle.sourceforge.net/turtle/reference.html#turtle.reference.expectation.actions

您可以在测试中创建一个辅助函数,根据需要修改 x。将 x 传递给该函数。

int function( int* x )
{
    *x = whatever;
    return 0;
}

MOCK_EXPECT(mock->f).calls( &function );

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    Fake-It 是一个简单的 C++ 模拟框架。它同时支持 GCC 和 MS Visual C++。 以下是您如何存根方法并使用 FakeIt 更改指向的对象:

    struct SomeClass {
        virtual int foo(int * x) = 0;
    };
    
    Mock<SomeClass> mock;
    When(Method(mock,foo)).AlwaysDo([](int * x) { (*x)++; return 0;});
    SomeClass &obj = mock.get();
    
    int num = 0;
    ASSERT_EQUAL(0, obj.foo(&num)); // foo should return 0;
    ASSERT_EQUAL(1, num);           // num should be 1 after one call to foo; 
    

    【讨论】:

    • 感谢您的回答,但它与海龟不同。我不能使用其他库。乌龟的期望看起来像: MOCK_EXPECT(SomeClass.x) .once() .with(&someValue) .returns(0);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-22
    • 2022-09-24
    • 1970-01-01
    • 1970-01-01
    • 2015-12-16
    • 1970-01-01
    相关资源
    最近更新 更多