I am having difficulties in figuring out how to mock the singleton class, and test it in another class. The goal is to verify that a method from a singleton class (Alarm) gets called from another class (CEvnts).
I was able to test this successfully by eliminating the singleton function, but since it is legacy code, I cannot change the structure.
Going through several articles and posts online, I have not found a clear answer. Does anyone know how to set up the Google Test for a singleton class? Any references or articles can be a big help.
Singleton Class:
class Alarm
{
public:
Alarm();
virtual ~Alarm();
// Singleton
static Alarm* find(void)
{
if (!Alarm_Instance)
{
Alarm_Instance = new Alarm();
}
return Alarm_Instance;
}
// Member methods
virtual ENUM_TYPE getType(ENUM_TYPE ENUM_ARG);
private:
static Alarm* Alarm_Instance;
};
ENUM_TYPE Alarm::getType(ENUM_TYPE ENUM_ARG)
{
return aMatch[ENUM_ARG].aType;
}
Mock:
class Alarm_Mock : public Alarm
{
public:
Alarm_Mock();
virtual ~Alarm_Mock();
MOCK_METHOD1(getType, ENUM_TYPE(ENUM_TYPE ENUMONE));
};
Google Test:
class Ev_test: public testing::Test
{
void SetUp()
{
mpsEV= new CEvents();
ON_CALL(msMock, getType(_)).WillByDefault(Return(SOME_ENUM));
}
void TearDown()
{
delete mpsEV;
}
protected:
Alarm_Mock msMock;
CEvents* mpsEV;
};
TEST_F(Ev_test, testGetFunctions)
{
EXPECT_CALL(msMock, getAlarmType(_))
.Times(1);
mpsEV->aMethod(arg1, arg2, arg3, arg4);
}
Class Method to Test - Does getType from Class Alarm get called?:
void CEvents::aMethod(arg1, arg2, arg3, arg4)
{
Alarm::find()->getType(arg1);
}