Reputation: 87
I'm using Google Test to perform tests over a class that might throw an exception. The method I'm testing is:
void SerialPortManager::OpenPort(PortID portNo) throw(){
try{
ports[portNo]->Open();
}
catch(exception &e){
throw;
}
}
And the test I'm using to test it is:
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;
}
I expected the test to be passed but instead I get:
terminate called after throwing an instance of 'SerialPortOpenErrorException'
what(): Error Opening Serial Port
¿How can I test that the exception is thrown?
Upvotes: 1
Views: 1327
Reputation: 254431
You have an exception specifier saying that the function won't throw anything:
void SerialPortManager::OpenPort(PortID portNo) throw()
^^^^^^^
But then you try throw an exception out of the function. That will result in terminate
being called.
If the function is supposed to throw, then remove the exception specifier. If it's not, then handle exceptions in some other way than rethrowing them.
Upvotes: 3