I have a class that exposes a public event named StatusChanged.
public event StatusChangedDelegate StatusChanged; |
The class that creates this class is supposed to wire this event to appropriate handlers. I'm trying to write a simple test that verifies this has occurred. However, the following line in a test:
Assert.IsTrue(target.StatusChanged != null); |
returns this error: "Error 8 The event 'NewDawnTechControls.NdtSessionController.StatusChanged' can only appear on the left hand side of += or -=."
Inside my class (with the event) I have an intercept method that is the one that actually raises the event, and in that method I have nearly the exact same statement:
if (StatusChanged != null) { StatusChanged( this, new StatusChangedEventArgs(message, status));} |
It works inside the class with the event, but not from outside. From outside the class, how can I verify the event has been wired
Thanks.

Test that an event has been wired to a handler?
Katou
Ugh!
Events are made to do this, no Requiring coupling only to the degree that the listeners need to know about an interface that exposes the event so they can register for it, or using an intermediary EventBroker class, or whatever. The event-generating class only needs to know to say RaiseMyEvent() and whoever is registered to handle the event will get the call, regardless if there is only one, or one thousand.
My original query was just about seeing from outside the event-generating class if an event had been registered for yet. It is just a small point to try to have more thorough unit testing.
vikassony
Since we need to wire multiple handlers to this event, we cannot use a delegate for this. I suppose I'm trying to test something that I can't really test.
Thanks.
Konstantin Triger
Thanks.
Ewa
Thanks,
Michael
GeoffMF
Well, in general this compiler error is correct .net behavior. As far as I understand how events are usually used is that the event is fired from inside the class that holds the event variable. For instance, consider a Button. You click on it in UI, then the Button class inside sees if there is a event registered (check for null) and if is, fire the event. Or there can be a method OnClick() that can be called from outside the class, it would check the event, etc. Delegates do not the limitation that you can't check for null from outside the class.
Also, if you want to assert whether the event was actually fired, i.e. be100% sure (checking for null means that event was just assigned, not necesserily fired) you may set some variable in the actualy event receiver method.
If you want to check just the assigntment from outside, remove the word 'event' from your event variable declaration so that it becomes: public StatusChangedDelegate StatusChanged. After that the code should compile fine.
Thanks,
Michael