chevron-thin-right chevron-thin-left brand cancel-circle search youtube-icon google-plus-icon linkedin-icon facebook-icon twitter-icon toolbox download check linkedin phone twitter-old google-plus facebook profile-male chat calendar profile-male
Welcome to Typemock Community! Here you can ask and receive answers from other community members. If you liked or disliked an answer or thread: react with an up- or downvote.
0 votes
I am using TypeMock for the first time, and am trying to mock an instance of the .Net SerialPort class for a listener i am writing. However when i add a handler to the SerialPort.DataReceived event, my tests are still failing when the event is fired (stating there are no handlers attached to the event). Below is my code:

Mock<SerialPort> mock;
IRfidListener listener;

[TestFixtureSetUp]
public void Setup()
{
mock = MockManager.MockObject<SerialPort>();
mock.ExpectGet("IsOpen", true);

listener = new ComPortListener(mock.MockedInstance);
}

[Test]
public void Start_attaches_to_port_DataReceived_event()
{
MockedEvent dataReceived = mock.ExpectAddEvent("DataReceived");
listener.Start();
dataReceived.Fire(this, EventArgs.Empty);
}
asked by jsearles (640 points)

2 Answers

0 votes
The reason you get this exception is that you must have the MockEvent declaration before you attach a listener to that event.

The code should be in the following order:
mock = MockManager.MockObject<SerialPort>();
mock.ExpectGet("IsOpen", true);

// Here we declare the event
MockedEvent dataReceived = mock.ExpectAddEvent("DataReceived");

// Now we use it
listener = new ComPortListener(mock.MockedInstance); 

listener.Start();
dataReceived.Fire(this, EventArgs.Empty); 

I'm not sure hoiw this reflects on your test(s) because the arraignment part of the test is spitted between the FixtureSetup and the actual test.
answered by dhelper (11.9k points)
0 votes
Thanks - that did it.

I was trying to reuse the mock objects, but i guess that causes problems.

Josh
answered by jsearles (640 points)
...