views:

67

answers:

3

Can I test the assertion that an event was fired? Something like this:

[TestMethod]
public void EventFiresWhenChangingProperty()
{
    var sut = new SystemUnderTest();
    var eventRegister = new EventRegister(sut.PropertyChanged);
    sut.AnyProperty = "new value";
    Assert.EventWasFired(eventRegister);
}

Of course I could create an event handler, that puts some record into the test context or in an instance variable that is only read by this specific test but this seems a little bit too much plumbing. I am looking for something like the code above.

A: 

Although at first it seems like "unneeded plumbing" code adding a listener to the event is actually a good idea and I think you should do that to test the event.

There are some mocking frameworks that enable you to do just that you want but it adds additional dependencies to your code.

Keep it simple - subscribe to the event.

Dror Helper
+3  A: 

I usually hook up an anonymous method as an event listener, and set a testable value in it, like so:

var sut = new SystemUnderTest();
bool eventWasRaised = false;
sut.PropertyChanged += (s, e) => eventWasRaised = true;    
sut.AnyProperty = "new value";
Assert.IsTrue(eventWasRaised);

That gives a minimal amount of plumbing. If you want to add some cleaning up, you can create a variable holding the event handler:

var sut = new SystemUnderTest();
bool eventWasRaised = false;
EventHandler eh = (s, e) => eventWasRaised = true;
sut.PropertyChanged += eh;  // attach event handler
sut.AnyProperty = "new value";
Assert.IsTrue(eventWasRaised);
sut.PropertyChanged -= eh;  // detach event handler
Fredrik Mörk
nice one. when writing the stuff above the idea of doing something with anonymous methods was already in my head... but in a very abstract shape.
Marc Wittke
A: 

I agree with Fredrik Mörk's solution and use it fairly often. One note: it's best to insert a Sleep of at least 20-30 milliseconds after the triggering action to ensure that enough time is given for the event handler to kick in - sometimes I've had race conditions develop.

Rich