1

我有2节课。

class SomeClass
{
public:
    int SomeFunction()
    {
        return 5;
    }
};


class AnotherClass
{
public:
    int AnotherFunction(SomeClass obj)
    {
        return obj.SomeFunction();
    }
};

我为 SomeClass 做了一个模拟类。

class MockSomeClass : public SomeClass
{
public:
    MOCK_METHOD0(SomeFunction, int());
};

现在我想在单元测试中,当我调用 AnotherClass.AnotherFunction 时,我会得到我自己选择的结果。AnotherFunction 使用 SomeClass.SomeFunction() 的函数。我嘲笑了SomeClass。我已经设置了当模拟对象的函数调用它时返回 10。但是当我运行单元测试时它返回 5(原始函数)。我该怎么办。下面是我写的单元测试。

[TestMethod]
    void TestMethod1()
    {
        MockSomeClass mock;
        int expected = 10;
        ON_CALL(mock, SomeFunction()).WillByDefault(Return(expected));
        AnotherClass realClass;
        int actual = realClass.AnotherFunction(mock);           
        Assert::AreEqual(expected, actual);
    };

我正在使用 Visual Studio 2008 和 gmock 1.6.0。我在做什么错。在 realClass.AnotherFunction 上,我想要 mock.SomeFunction() 的模拟输出。

4

1 回答 1

3

问题是 SomeClass::SomeFunction(...) 不是虚拟的,将其设为虚拟并且它将起作用。

更新:

还有一个更根本的错误导致它失败,那就是方法签名

int AnotherFunction(SomeClass obj)

它创建了一个新的 SomeClass 对象实例,该实例又会导致调用正常的 SomeFunction ,您应该改为传递对模拟类的引用作为参数。

int AnotherFunction(SomeClass* obj)

并使用

int actual = realClass.AnotherFunction(&mock);
于 2012-02-09T12:42:42.853 回答