Reputation: 4970
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?
I don't think it's possible to do this solely using google-mock macros.
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
.
But that still doesn't help you access the private member NetworkClass b
for the purpose of the test.
Upvotes: 0
Views: 1284
Reputation: 989
You cannot mock b
as it is. 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
. Then you can pass aa raw pointer (better a smart pointer like std::unique_ptr) or a reference to class A
. This input can be either your real implementation NetworkClass
or your mock 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, e.g. 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. If you still want to do this you could check this answer (written for C# instead of C++ but still usable).
P.S. To use the override keyword you will need to compile with C++11 support.
Upvotes: 1