How to Assert that an Event Has been Subscribed To with FakeItEasy?
Asked Answered
F

2

7

I have a fake class that contains an event. My code should subscribe to that event and I want to test that. I'm using FakeItEasy with NUnit and I'm looking for a way to check that my code actually subscribes to that event.

Thanks!

Fredricfredrick answered 21/12, 2011 at 15:5 Comment(1)
Just a suggestion: instead of testing that your code subscribes to event just test that when it receives such event it actually does something. This way you can have test like "When event is raised then Foo is called" which describes what should happen.Sibilla
E
13

I agree with the comment suggesting that you'd rather just raise the event and check that the handler you want to have subscribed has been invoked. But there is a way to check wether a handler was attached, thought not very pretty:

public interface IHaveAnEvent
{
    event EventHandler MyEvent;
}

// In your test...
var fake = A.Fake<IHaveAnEvent>();

var handler = new EventHandler((s, e) => { });

fake.MyEvent += handler;

A.CallTo(fake).Where(x => x.Method.Name.Equals("add_MyEvent")).WhenArgumentsMatch(x => x.Get<EventHandler>(0).Equals(handler)).MustHaveHappened();

If you just want to check that any handler was attached you can omit the "WhenArgumentsMatch" part.

Embezzle answered 23/12, 2011 at 14:20 Comment(0)
M
0

The maximum you can do is to check if the event equals to null, it will return whether something is subscribed to it or not.
Otherwise, you can't know which or how many handlers are subscribed to an event.

Marnamarne answered 21/12, 2011 at 15:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.