Testing event handling with mocks using nunit
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?
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.
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
精彩评论