简体   繁体   English

google mock - 如何在测试中模拟 class 拥有的 object

[英]google mock - how to mock object owned by class under test

In this example在这个例子中

class A
{
public:
    A();
    ~A();

    virtual void func1();
    virtual void func2();

protected:
    virtual void func3();
private:
    // How do I mock this
    NetworkClass b;
}

How do I mock NetworkClass b object?如何模拟NetworkClass b object?

I don't think it's possible to do this solely using google-mock macros.我认为仅使用 google-mock 宏是不可能做到这一点的。 You'd have to redefine the identifier NetworkClass to actually mean NetworkClassMock and then (for purpose of the test) rename the original NetworkClass to something else like NetworkClass_Orig .您必须重新定义标识符NetworkClass以实际表示NetworkClassMock ,然后(出于测试目的)将原始NetworkClass重命名为NetworkClass_Orig之类的其他名称。

But that still doesn't help you access the private member NetworkClass b for the purpose of the test.但这仍然不能帮助您访问私有成员NetworkClass b以进行测试。

You cannot mock b as it is.您不能按原样模拟b You will need to use Dependency Injection .您将需要使用依赖注入

First you will need to specify a Base Class (or interface) and derive your NetworkClass and NetworkClassMock from INetworkClass .首先,您需要指定 Base Class (或接口)并从INetworkClass派生您的NetworkClassNetworkClassMock Then you can pass aa raw pointer (better a smart pointer like std::unique_ptr ) or a reference to class A .然后你可以传递一个原始指针(最好是像std::unique_ptr这样的智能指针)或对class A的引用。 This input can be either your real implementation NetworkClass or your mock NetworkClassMock .此输入可以是您的实际实现NetworkClass或您的模拟NetworkClassMock

See this example:看这个例子:

#include <iostream>

class INetworkClass
{
public:
    virtual void doSomething() = 0;
};

class NetworkClass : public INetworkClass
{
public:
    void doSomething() override {std::cout << "Real class" << std::endl;} ;
};

class NetworkClassMock : public INetworkClass
{
public: 
    void doSomething() override {std::cout << "Mock class" << std::endl;};
};

class A
{
public:
    A(INetworkClass& b) : b(b) {};
    ~A() {};

    void func1() {b.doSomething();};

private:
    // How do I mock this
    INetworkClass& b;
};

int main(){
  NetworkClass real_class;
  NetworkClassMock mock_class;

  A a1(real_class);
  A a2(mock_class);

  a1.func1();
  a2.func1();

  return 0;
}

If you just want to access your private member, eg to read it's value after doing some tests you should redesign your code.如果您只想访问您的私人成员,例如在进行一些测试后读取它的值,您应该重新设计您的代码。 Accessing private members from outside your class is not a good design.从 class 外部访问私有成员不是一个好的设计。 If you still want to do this you could check this answer (written for C# instead of C++ but still usable).如果你仍然想这样做,你可以检查这个答案(写为 C# 而不是 C++ 但仍然可用)。

PS To use the override keyword you will need to compile with C++11 support. PS 要使用 override 关键字,您需要使用 C++11 支持进行编译。

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

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