views:

52

answers:

2

I need to create some unit tests that confirm that instance of a class responds appropriately to an event raised by another object. Passing in a mock of the 'watched' object is easy enough, but as far as I can tell, mocks in nunit don't provide a means of having the mock raise an event.

I'm considering using reflection to directly invoke the event handler on the object I'm testing, passing a reference to the mock as the 'sender', but this doesn't effectively test that my object correctly hooked the events in the first place (although now I think about it, this should probably be tested separately anyway).

It does seem like a bit of a hack, but I can't see another way of doing it; is there a better way? Also, is it possible for a mock to check that an event is hooked?

+1  A: 

I use Rhino Mocks for creating mocks, and they handle events very nicely: http://ayende.com/Wiki/Default.aspx?Page=Rhino+Mocks+Events&AspxAutoDetectCookieSupport=1

Grzenio
Cool, never noticed Rhino could do that; unfortunately, I'm required to use nUnit in this instance.
Flynn1179
Hi @Flynn1179, NUnit? Usually you would use Rhino Mocks on top of NUnit. Are you using the mocking framework that ships with NUnit?
Grzenio
Yes; However, given that all our current tests don't use Rhino, I'd be hard pushed to convince my team/boss to use Rhino for some tests and nUnit's mocks for others, or to switch over to Rhino completely.
Flynn1179
+1  A: 

The RhinoMock code is great for verifying that subscription happens or for verifying that events are raised, but not so great for raising events itself.

I have a similar issue. I got around it by writing my own little stub class that implements the event aggregator interface and allows me to raise an event from the test. Sometimes writing your own test code can be easier than messing around with mocking frameworks, which weren't really designed to do this.

The behaviour of your class is only valuable if it hooks to the events and responds to them, so I don't think there's much point in testing these separately.

Lunivore
I'm guessing the answer to my original question is a simple 'no', although I should have specified I'm pretty much restricted by circumstance to nunit's mocks. Looks like I'm going to have to go with the stub option.
Flynn1179