Below is one of the line in my method. Here i have to mock the method "findChild" and make "Chino::mock_Button" instance to be assigned to the "close_button". This is my requirement.
Chino::Button* close_button = findChild<Chino::Button>("CloseButton");
Methods I tried:
Since findChild is a template, I can't mock it. So I changed the implementation of findchild template to specialize to Chino::Button type and mock the new function "getChinoButtonInstance(QString,bool)" and make that to return the Chino::Mock_button instance rather than Chino::Button instance.
template<>
inline Chino::Button* Mediator::findChild<Chino::Button>(const QString &name, bool recursive)
{
return getChinoButtonInstance(name,recursive);
}
Then, in the UnitTestClass I have mocked the "getChinoButtonInstance".
MOCK_METHOD2(getChinoButtonInstance,Chino::Mock_Button*(QString,bool));
and EXPECT_CALL is :
EXPECT_CALL(*wLighting,getChinoButtonInstance("a",true)).Times(testing::AtLeast(1)).WillOnce(testing::ReturnPointee(&wLighting->sourceButtonMock));
Here instead of ReturnPointee, I have tried with Return and ReturnRef. In all the cases findchild assigns "close_button" to nullptr.
We have a separate store class created. Just to put and get the values.Here before calling the findchild method, I will be storing the Chino::mockButton instance in the Store class. So the findchild class is modified as :
template<>
inline Chino::Button* Mediator::findChild<Chino::Button>(const QString &name, bool recursive)
{
HarmanUTestStore *store=HarmanUTestStore::instance();
Chino::Mock_Button *val=dynamic_cast<Chino::Mock_Button*>(store->getMockInstance());
return val;
}
Here the problem is Object Slicing. I can see the debugger showing the "Chino::MockButton" instance is being returned when "store->getMockInstance()" is called. But I am not sure where the problem is, debugger is not showing the value of "val" and it is directly stepping into the findChild statement and having the object of Chino::Button instance assigned to "close_button" instead of Chino::MockButton instance. I am sure the problem is Object Slicing but dont know how to solve this issue.
I was doing wrong casting in the second approach.
Chino::Button *val=static_cast<Chino::Mock_Button*>(store->get(KEY_CHINO_CLOSE_BUTTON_INSTANCE));
This fixed my issue.