简体   繁体   English

gmock:为什么EXPECT_CALL无法在我的测试中检测到函数调用?

[英]gmock: Why isn't EXPECT_CALL detecting the function call in my test?

The text "callback called" from Callback() prints to console, but gmock fails the test saying that no callback happened. 来自Callback()的文本“callback called”打印到控制台,但gmock未通过测试表明没有回调发生。 What am I doing wrong? 我究竟做错了什么?

class MyClass
{
    public:
        MyClass() { };
        virtual ~MyClass() { };
        void Callback() { printf("callback called\n"); };
};

class MyClassMock : public MyClass
{
public:
    MOCK_METHOD0(Callback, void());
};

class Caller
{
public:
    Caller(MyClass *myClass) { m_myClass = *myClass; };
    void Call() { m_myClass.Callback(); };
private:
    MyClass m_myClass;
};

TEST(BasicTest, Positive)
{
    MyClassMock mock;
    EXPECT_CALL(mock, Callback()).Times(1);

    Caller caller(&mock);
    caller.Call();
}

Your 你的

void Callback();

method is not declared virtual . 方法未声明为virtual So you can't mock it that way with a simple derived mock class. 因此,您不能使用简单的派生模拟类来模拟它。

To cite from the google-mock documentation 引用Google-mock文档

Google Mock can mock non-virtual functions to be used in what we call hi-perf dependency injection. Google Mock可以模拟我们称之为hi-perf依赖注入的非虚函数。

In this case, instead of sharing a common base class with the real class, your mock class will be unrelated to the real class, but contain methods with the same signatures. 在这种情况下,不是与真实类共享公共基类,而是模拟类与真实类无关,但包含具有相同签名的方法。

The consequence is you have to realize this with a template. 结果是您必须使用模板来实现这一点。 There's a concise example given at the documentation section linked from above. 在上面链接的文档部分给出了一个简明的例子。


Trying to "translate" their sample to your case, it should look like 尝试将其样本“翻译”为您的案例,它看起来应该像

class MyClass {
    public:
        MyClass() { };
        virtual ~MyClass() { };
        void Callback() { printf("callback called\n"); };
};

class MyClassMock {
public:
    MOCK_METHOD0(Callback, void());
};

template<class T>
class Caller {
public:
    Caller(T& myClass) : m_myClass(myClass) {}
    void Call() { m_myClass.Callback(); }
private:
    T& m_myClass;
};

TEST(BasicTest, Positive) {
    MyClassMock mock;
    EXPECT_CALL(mock, Callback()).Times(1);

    Caller<MyClassMock> caller(mock);
    caller.Call();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM