C++ 谷歌测试不处理异常
我正在使用GoogleTest对可能引发异常的类执行测试。我正在测试的方法是:C++ 谷歌测试不处理异常,c++,unit-testing,exception,C++,Unit Testing,Exception,我正在使用GoogleTest对可能引发异常的类执行测试。我正在测试的方法是: void SerialPortManager::OpenPort(PortID portNo) throw(){ try{ ports[portNo]->Open(); } catch(exception &e){ throw; } } 我用来测试它的测试是: TEST(SerialPortManagerTest,ExceptionCatchedOnFailedOpen) { PortID p
void SerialPortManager::OpenPort(PortID portNo) throw(){
try{
ports[portNo]->Open();
}
catch(exception &e){
throw;
}
}
我用来测试它的测试是:
TEST(SerialPortManagerTest,ExceptionCatchedOnFailedOpen) {
PortID portID = COM1;
MockSerialPort* port1 = new MockSerialPort();
EXPECT_CALL(*port1, Open()).Times(Exactly(1)).WillOnce(Throw(SerialPortOpenErrorException()));
MockSerialPort* port2 = new MockSerialPort();
MockSerialPort* port3 = new MockSerialPort();
MockSerialPortFactory portFactory;
EXPECT_CALL(portFactory, CreateSerialPort(_)).Times(3).WillOnce(
ReturnPointee(&port1)).WillOnce(ReturnPointee(&port2)).WillOnce(
ReturnPointee(&port3));
SerialPortManager* serialPortManager = new SerialPortManager(
(SerialPortFactoryInterface*) &portFactory);
EXPECT_ANY_THROW(serialPortManager->OpenPort(portID));
delete serialPortManager;
}
我希望考试能通过,但我得到了:
terminate called after throwing an instance of 'SerialPortOpenErrorException'
what(): Error Opening Serial Port
?如何测试是否抛出异常?您有一个异常说明符,表示函数不会抛出任何异常:
void SerialPortManager::OpenPort(PortID portNo) throw()
^^^^^^^
但随后您尝试从函数中抛出一个异常。这将导致调用terminate
如果函数应该抛出,则删除异常说明符。如果不是,则以其他方式处理异常,而不是重新引用异常。无论如何,我都会删除异常说明符。