How to Google Mock a method called from a struct
Let's have this example:
Class A{
public:
int Get();
}
In another file:
A a;
struct B{
int res = a.Get();
}
I would need to Googl开发者_JS百科e Mock Get method, however, I will also need to call the real one. I have tried with #ifdef, and it seems to work. Then I decided to mock it in the #ifdef section but it does nothing.
#ifdef UNIT_TEST
MOCK_METHOD0(A,Get);
#else
int A::Get(){....}
#endif
What am I doing wrong? Is there any cleaner way to do it? Please, any help would be much appreciate it.
You did it wrongly. This is how it should be done :
1) Header file :
struct A
{
#ifdef UNIT_TEST
MOCK_METHOD0(Get, int());
#else
int Get();
#endif
};
2) Source file :
#ifndef UNIT_TEST
int A::Get()
{
// ...
}
#endif
It seems that Google Mock has changed quite a bit. Now you can try delegating to a real object described in the cookbook. You can continue setting and checking expectations on your mock, but the calls will also be handled by the real thing.
class MockA : public A
{
public:
MockA()
{
ON_CALL(*this, Get()).WillByDefault(Invoke(&real, &A::Get));
}
MOCK_METHOD0(Get, int());
private:
A real;
};
Header file:
class A{
public:
int Get();
};
A a;
Source file:
int A::Get(){
....
}
struct B{
return res = a.Get();
};
精彩评论