2
我正在使用谷歌Mock框架來執行串口管理器類的單元測試。我使用的類圖使用谷歌模擬無效的指針錯誤
一個我爲了測試串口管理準備測試的是:
TEST(SerialPortManagerTest,AllPortsAreClosedAtInit){
MockSerialPort port1;
EXPECT_CALL(port1, IsOpen()).Times(Exactly(1)).WillOnce(Return(false));
MockSerialPort port2;
EXPECT_CALL(port2, IsOpen()).Times(Exactly(1)).WillOnce(Return(false));
MockSerialPort port3;
EXPECT_CALL(port3, IsOpen()).Times(Exactly(1)).WillOnce(Return(false));
SerialPortInterface* port1Ptr=&port1;
SerialPortInterface* port2Ptr=&port2;
SerialPortInterface* port3Ptr=&port3;
MockSerialPortFactory portFactory;
EXPECT_CALL(portFactory, CreateSerialPort(_)).Times(3).
WillOnce(ReturnPointee(&port1Ptr)).
WillOnce(ReturnPointee(&port2Ptr)).
WillOnce(ReturnPointee(&port3Ptr));
SerialPortFactoryInterface* portFactoryPtr=&portFactory;
SerialPortManager* serialPortManager =new SerialPortManager(portFactoryPtr);
EXPECT_FALSE(serialPortManager->GetPort(COM1)->IsOpen());
EXPECT_FALSE(serialPortManager->GetPort(COM2)->IsOpen());
EXPECT_FALSE(serialPortManager->GetPort(COM3)->IsOpen());
}
當我執行的測試返回無效指針錯誤:
free(): invalid pointer: 0xbfc8d8e4 ***
看問題,我發現,如果我評論說,刪除serialPortFactory在SerialPortManag線路沒有返回錯誤呃破壞者。
SerialPortManager::~SerialPortManager() {
for (int i = 0; i < PORT_COUNT; i++) {
delete ports[i];
}
//delete serialPortFactory;
}
¿我該如何模擬serialPortFactory而不會收到此無效指針錯誤?