jmzagorski
jmzagorski

Reputation: 1155

Unit Test an Event Listener is attaching/detaching an event to a class

I am stuck on one unit test, testing that an event was attached by an event listener to a class and detached. I cannot figure out how to do this and I have looked in many forums. The EmailEventListener attaches the event in the constructor to the fakeClass and detaches in the Detach() method. It also holds the method that is called when the event is fired. I am using FakeItEasy to create the fakeclass. Any thoughts? Thank you!

[TestMethod]
public void EmailEventListener_AttachedSubscription_ToClass_Successfully()
{
    EmailEventListener<ConcreteClass> realListener = new EmailEventListener<ConcreteClass>(fakeClass, A.Dummy<IEmailSender>());

    // Assert that fakeClass has the event

    realListener.Detach();

    // Assert that fakeClass does not have the event (probably in another test, but just wanted to show it here)

}

Upvotes: 0

Views: 385

Answers (1)

Servy
Servy

Reputation: 203834

To assert that an event handler runs, have the handler that you attach do something that you can assert is done, say flipping a boolean handlerExecuted variable from false to true.

To assert that it is detached, do the same thing, but invert the assertion. (Assert that handlerExecuted is false rather than true.)

Upvotes: 1

Related Questions