简体   繁体   English

如何使用Google Test模拟正在测试的类中的方法

[英]How to mock methods in class under test with google test

Consider this class under test: 考虑一下正在测试的此类:

class A
{
public:
    bool isTrue();
    void doSomething();
};

I want to test doSomething which calls isTrue in its implementation. 我想测试在其实现中调用isTrue doSomething

But I also want to set expectations on the isTrue method. 但是我也想对isTrue方法设定期望。 Is there a best practice with google test how one can mock methods of the class under test? Google测试是否有最佳做法,该如何模拟被测类的方法?

Turning my comment into an answer... 将我的评论变成答案...

There's a little hack you can use. 您可以使用一些技巧。 Define a derived class like so: 像这样定义派生类:

class B : public A {
public:
    MOCK_METHOD0(isTrue, bool());

    using A::doSomething;
};

This obviously only works if isTrue is virtual . 这显然仅在isTruevirtual时才有效。

Beware: Check your company's testing guidelines regarding "code made especially for testing" instead of testing the real code. 当心:请检查贵公司关于“专门为测试而编写的代码”的测试准则,而不要测试真实的代码。 In your situation (legacy codebase) this might be okay. 在您的情况下(旧版代码库),这可能没问题。

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

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