需要谷歌模拟帮助,

Google Mock Help Required,

本文关键字:帮助 模拟 谷歌      更新时间:2023-10-16

我有两个类。

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);
    };

我使用的是visualstudio2008和gmock1.6.0。我在做什么不对。在realClass.AnotherFunction上,我想要mock的mock输出。SomeFunction()。

问题是SomeClass::SomeFunction(…)不是虚拟的,让它成为虚拟的,它就会工作。

更新:

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

int AnotherFunction(SomeClass obj)

它创建了一个新的SomeClass对象实例,从而导致调用普通的SomeFunction,您应该将对模拟类的引用作为参数传递。

int AnotherFunction(SomeClass* obj)

并使用调用它

int actual = realClass.AnotherFunction(&mock);