Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing that an event has an EventHandler assigned

I'm wanting to test that a class has an EventHandler assigned to an event. Basically I'm using my IoC Container to hook up EventHandlers for me, and I'm wanting to check they get assigned properly. So really, I'm testing my IoC config.

[Test]
public void create_person_event_handler_is_hooked_up_by_windsor()
{
    IChangePersonService changePersonService = IoC.Resolve<IChangePersonService>();

    // check that changePersonService.PersonCreated has a handler attached
}

I'm not sure how to test that changePersonService.PersonCreated has anything attached to it though.

Any ideas?

Thanks.

like image 688
mattcole Avatar asked Oct 27 '22 07:10

mattcole


1 Answers

Not questioning what you pretend with this, the only way of testing and enumerating the registered events is if your register them in your own collection.

See this example:

public class MyChangePersonService : IChangePersonService
{
    private IList<EventHandler> handlers;

    private EventHandler _personEvent;

    public event EventHandler PersonCreated
    {
        add
        {
            _personEvent += value;
            handlers.Add(value);
        }

        remove
        {
            _personEvent -= value;
            handlers.Remove(value);
        }
    }

    public IList<EventHandler> PersonEventHandlers { get { return handlers; } }

    public MyChangePersonService()
    {
        handlers = new List<EventHandler>();
    }

    public void FirePersonEvent()
    {
        _personEvent(this, null);
    }
}

Then you could access the registered handlers with prop PersonEventHandlers.

Can you implement something like this?

like image 127
bruno conde Avatar answered Nov 15 '22 06:11

bruno conde