Click here to Skip to main content
15,881,838 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a class that raises an even when its internal state changes (broadly similar to INotifyPropertyChange but slightly different).

How should I write a unit test that verifies that this event is indeed raised?
(There's nothing in the same model as "ExpectedException" for events?)
Posted
Comments
Sergey Alexandrovich Kryukov 27-Aug-14 11:45am    
I'm not sure you really understand the purpose of unit testing. It does not test everything. Nothing tests everything, ever. People use it to verify that the unit works in all aspects, independent from the pieces of software using this unit. Is some event is invoked or not is a different thing. Some events can only be invoked by the physical use of the mouse. In this case, the test should change the state and detect some side effect which happens only in the handler...
—SA
Duncan Edwards Jones 27-Aug-14 11:49am    
No indeed - but the event is only raised under certain circumstances and I want to test that - i.e. circumstances not met, no event was raised. Circumstances met, event was raised.

I am testing the class in isolation.

1 solution

Hello,

You could do it using delegates in your unit tests.

for example:

[TestMethod]
public void EventShouldBeRaised()
{
    ClassToTest classToTest = new ClassToTest();
    bool eventRaised = false;

    classToTest.EventRaised += delegate(object sender, ClassToTestEventArgs e)
    {
        eventRaised = true;
    };

    classToTest.Property1 = "somthing";
    // this property raises an event, test if the boolean is set to true in the delegate call.
    Assert.AreEqual(eventRaised, true);
}

[TestMethod]
public void EventShouldNotBeRaised()
{
    ClassToTest classToTest = new ClassToTest();
    bool eventRaised = false;

    classToTest.EventRaised += delegate(object sender, ClassToTestEventArgs e)
    {
        eventRaised = true;
    };

    classToTest.AnotherProperty = "somthing";
    // This property does not raise the event, so we test that the eventRaised boolean is false.
    Assert.AreEqual(eventRaised, false);
}


Valery.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900