问题
I'm trying to pass a mocked object to another object's method and call it, i get the same result as I would call real method.
fooa.h - this is the real class
#ifndef FOOA_H
#define FOOA_H
class FooA
{
public:
FooA();
virtual int method(int a, int b, int c, int d);
};
#endif // FOOA_H
fooa.cpp
#include "fooa.h"
FooA::FooA()
{
}
int FooA::method(int a, int b, int c, int d)
{
return a+b+c+d;
}
mockedfooa.h - mocked version of fooa
#ifndef MOCKEDFOOA_H
#define MOCKEDFOOA_H
#include "fooa.h"
#include <gmock/gmock.h>
class MockedFooA : public FooA
{
public:
MOCK_METHOD4( method, int(int a, int b, int c, int d) );
};
#endif // MOCKEDFOOA_H
calculator.h this class invokes method from FooA class
#include "fooa.h"
#include <iostream>
class Calculator
{
public:
Calculator()
{ }
void doCalc(FooA foo)
{
int a = 3, b =4 ,c = 12, d = 41;
std::cout<<foo.method(a,b,c,d)<<std::endl;
}
};
And my main function
#include "MockedFooA.h"
#include "calc.h"
using ::testing::_;
using ::testing::Return;
using namespace std;
int main(int argc, char *argv[])
{
Calculator oCalc; // object that uses the oFoo.method
FooA oFoo;//not mocked
oCalc.doCalc(oFoo);
MockedFooA oMockedFoo ; // mocked
ON_CALL(oMockedFoo,method(_,_,_,_)).WillByDefault(Return(20));
oCalc.doCalc(oMockedFoo);
}
The output is
60
60
so it looks like even though it is stubbed doCalc still invokes the real method.
And my question is: Why when i'm passing mocked object to doCalc method isn't calling stubbed method?
回答1:
The problem is that you're passing the mocked object by value. Since mock objects exploit the dynamic binding provided by inheritance, you need to pass them around using references or pointers. Otherwise you'll end up slicing your objects.
To achieve the desired behavior, change your doCalc
method to take the FooA
parameter by-reference instead of by-value. Like this:
void doCalc(FooA& foo)
来源:https://stackoverflow.com/questions/23063013/gmock-passing-a-mocked-object-into-another-and-calling-a-stubed-method-is-still