我试图模拟系统的fun、ioctl和socket,但它总是调用系统函数的原始定义。下面是我使用gmock编写的gtest代码。
请检查一下代码,帮我找出哪里出了问题。有没有办法在单元测试中使用gmock模拟系统函数?如果有,请提供给我一个模仿系统功能的示例代码。
在test.hpp文件中
class SystemFun
{
public:
virtual ~SystemFun() {}
virtual int ioctl(int inetSocket, int counters, struct ifreq *device) = 0;
virtual int socket(int domain, int type, int protocol) = 0;
};
class SystemFunMock : public SystemFun
{
private:
static SystemFunMock *oSystemFunMockInstance;
static bool instanceFlag;
public:
virtual ~SystemFunMock() { instanceFlag = false; }
MOCK_METHOD3(ioctl, int(int inetSocket, int counters ,struct ifreq *device));
MOCK_METHOD3(socket, int(int domain, int type, int protocol));
static SystemFunMock *getInstance()
{
if (!instanceFlag)
{
oSystemFunMockInstance = new SystemFunMock();
instanceFlag = true;
}
return oSystemFunMockInstance;
}
};
In the test.cpp file the code
bool SystemFunMock::instanceFlag = false;
SystemFunMock* SystemFunMock::oSystemFunMockInstance = NULL;
int socket(int domain, int type, int protocol)
{
SystemFunMock* oSystemFunMock = SystemFunMock::getInstance();
return oSystemFunMock->socket(domain, type, protocol);
}
int ioctl(int inetSocket, int counters, struct ifreq *device)
{
SystemFunMock* oSystemFunMock = SystemFunMock::getInstance();
return oSystemFunMock->ioctl(inetSocket, counters, device);
}
TEST_F(EtherPortUT, linuxHalCommonTest)
{
SetUp();
SystemFunMock* oSystemFunMock = SystemFunMock::getInstance();
{
InSequence s;
EXPECT_CALL(*oSystemFunMock, ioctl(_,_,_))
.WillOnce(Return(0))
.WillOnce(Return(-1));
EXPECT_CALL(*oSystemFunMock, socket(_,_,_))
.WillOnce(Return(-1));
}
.....
pLNXNetIface->getLinkSpeed( 356, &speed ); // this fun def has 2 ioctl calls but calling the original function.
pLNXNetIface->watchNetLink( iPort ); // this fun def has socket call.
...
}
Definition of the functions getLinkSpeed
bool LinuxNetworkInterface::getLinkSpeed( int sd, uint32_t *speed )
{
struct ifreq ifr;
struct ethtool_cmd edata;
ifr.ifr_ifindex = ifindex;
if( ioctl( sd, SIOCGIFNAME, &ifr ) == -1 )
{
GPTP_LOG_ERROR
( "%s: SIOCGIFNAME failed: %s", __PRETTY_FUNCTION__,
strerror( errno ));
return false;
}
ifr.ifr_data = (char *) &edata;
edata.cmd = ETHTOOL_GSET;
if( ioctl( sd, SIOCETHTOOL, &ifr ) == -1 )
{
GPTP_LOG_ERROR
( "%s: SIOCETHTOOL failed: %s", __PRETTY_FUNCTION__,
strerror( errno ));
return false;
}
...
}发布于 2019-09-17 21:17:13
你不能mock a free function。您必须使用接口并使用接口调用函数
bool LinuxNetworkInterface::getLinkSpeed( int sd, uint32_t *speed )
{
...
if(m_pSystemFun->ioctl( sd, SIOCGIFNAME, &ifr ) == -1 )您必须为LinuxNetworkInterface提供某种方法来获取指向SystemFun的指针或引用。在您的测试中,您将向LinuxNetworkInterface提供模拟类。在您的实际应用程序中,您为LinuxNetworkInterface提供了一个实际的实现。
看起来你是在正确的轨道上。但接口SystemFun不仅用于测试,还可用于应用程序中。
https://stackoverflow.com/questions/57950808
复制相似问题