I'm developing some unit tests on a serial application in c++ using google mock framework.
The mock I've built for my serial port interface is:
class MockSerialPort: public SerialPortInterface {
public:
MOCK_METHOD0(Open, void());
MOCK_METHOD0(IsOpen,bool());
MOCK_METHOD4(Configure,void(int,int,int,SerialParity));
MOCK_METHOD0(Close,void());
MOCK_METHOD0(Read,queue<char>());
MOCK_METHOD1(RegisterSerialObserver,void(SerialObserver*));
MOCK_METHOD0(NotifySerialObserver,void());
MOCK_METHOD0(Die, void());
virtual ~MockSerialPort() {Die(); }
};
The implementation of NotifySerialObserver in my real implementation is:
void UnixSerialPort::NotifySerialObserver(){
this->serialManager->HandleSerialEvent(this->portID);
}
And the test I'm using is:
TEST(SerialPortManagerTest,PortReadThrowsExceptionOnReadError){
PortID portID=COM1;
MockSerialPort* port1=new MockSerialPort();
EXPECT_CALL(*port1, Read()).Times(Exactly(1)).WillOnce(Throw(SerialPortReadErrorException()));
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);
<<<Need to add EXPECT_CALL on *port1->NotifySerialObserver() that invokes serialPortManager->HandleSerialEvent(COM1)>>>>
serialPortManager->OpenPort(portID);
EXPECT_THROW(port1->NotifySerialObserver(),SerialPortReadErrorException);
delete serialPortManager;
}
I need to test that when port1->NotifySerialObserver() is called serialPortManager reads from port1. Is there a way of invoke serialPortManager->HandleSerialEvent(COM1) from the mocked serial port?
EDIT This is the serialPortManager constructor
SerialPortManager::SerialPortManager(
SerialPortFactoryInterface* serialPortFactory,SerialParserInterface* serialParser) {
this->serialPortFactory = serialPortFactory;
this->serialParser=serialParser;
for (int i = 0; i < PORT_COUNT; i++) {
ports[i] = serialPortFactory->CreateSerialPort((PortID) i);
cout << "Created port " << i << endl;
ports[i]->RegisterSerialObserver(this);
}
}