dimanche 22 février 2015

how to mock global free function using gmock

I am using VS2005, and gmock 1.6. I am facing a problem to mock free global functions. I looked into google cookbook, their solution requires me to change the original sources and I don't want to do that. I tried to mock it using global mock object, but in that case I get memory leaks or the error that the mock object should be deleted but never is.


So, the problem is as follows:


I have a global function:



A* foo();


I have a mock class



class MockA : public A {
public:
MOCK_METHOD0 (bar1, bool());
MOCK_METHOD0 (bar2, bool());


};


In the sources, the global function is used in the following manner:



if (foo()->bar1()){
// do something
}

if (foo()->bar2()){
// do something
}


I cannot find a way to mock this behavior. I tried to wrap the global function "foo()" in an interface class and used global mock object to access it but I get memory leaks when TearDown() is called. Maybe I didn't do it properly. I did it like this:



struct IFoo {
virtual A* foo() = 0;
virtual ~IFoo() {}
};

struct FooMock : public IFoo {
FooMock() {}
virtual ~FooMock() {}
MOCK_METHOD0(foo, A*());
};

FooMock fooMock; // global mock object

// foo() implementation
A* foo() {
return fooMock.foo();
}


In the SetUp() function, I set Expectations on the global object like



EXPECT_CALL(fooMock,foo())
.Times(1)
.WillOnce(Return(&mockObj));


where mockObj is declared in the Test class. TEST(..., instA) {



// ...
}


I cannot change the original sources, so what other options do we have?


Aucun commentaire:

Enregistrer un commentaire