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
hi, I'm looking for a way to raise events from a mocked method. I'm trying to test an event handler without involving the object that raises the event.
asked by megagreg (640 points)

2 Answers

0 votes
Hi,
This really depends on your code and how accessible the events are, and what you are testing.

:idea: A simple answer to your question is to use the DynamicReturnValue, you can then put any code you want in the delegate.

:idea: Of course if you are just trying to test how you code runs with events, it is better to just raise the event from within the test.

public void MyTestEventHandler(object sender, MyEventArgs e)
{
}

[Test]
public void TestRaiseEvent()
{
   // Natural Mocks - expect one call of event handler
   using (RecordExpectations recorder = RecorderManager.StartRecording())
   {
        MyTestEventHandler(null,null); // don't care about arguments
   }

   TestObject theObject = new TestObject();
   theObject.MyEvent += MyTestEventHandler;
   theObject.MyEvent(this,new MyEventArgs());
   
   // make sure that our method has been called
   MockManager.Verify(); 
}


You can of course use a 'real' event handler method or write one just for the test.

The Reflective TypeMock equivalent is:
Mock theMock = MockManager.Mock(this.GetType());
theMock.ExpectCall("MyTestEventHandler");
answered by scott (32k points)
0 votes
Thanks for the quick response. I think the dynamic return value idea might work, but I got through the problem a different way in the meantime . Here's my situation: I have a (lets call it a boss) class that creates worker threads. The class containing the worker method (the class I wanted to mock) is instantiated in the boss class, so I can't make a stub to change it's behavior. The last thing the worker thread does is raise an event to notify listeners of it's completion. the boss class has an event handler(the function I'm testing) that starts a new worker to replace the one that's finished.

If I use the dynamic return value, will I be able to call the protected OnWorkerFinished method to raise the event (or just raise it manually)?

What I ended up doing is just including the worker class in the test. I mocked all the calls it made to other classes, and counted unmocked calls to the worker's method, then after running the boss for a period of time, I checked that more than one call was made to the worker's method. I'll check out the dynamic return value thing next time I come accross this situation.
answered by megagreg (640 points)
...