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.