views:

1076

answers:

4

Hi,

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.

A: 

Sounds like you are trying to prod some information out of your object in order to assert it is one thing or another. Note that this is not necessarily unit testing, because you are not testing functionality.

If you must test this, seems like you will need to open a public API in IChangePersonService in order to get the registered event handlers.

Yuval A
A: 

It looks to me like you're attempting to unit test Castle Windsor. Since it probably already has unit tests, I think this is a waste of effort. You'd be better off testing that your object raises the appropriate events at the correct times (probably by registering a mock object as the event handler).

Roger Lipscombe
A: 

It's not really unit testing, it's an integration test. And I'm not testing Castle Windsor, but rather my configuration of it. I'm testing that all my decoupled classes are being hooked up as I intend.

Ultimately, I want to test that my configuration is correctly hooking events up as I want, but I'm not sure that C# will let me without changing my API as Yuval says.

mattcole
+1  A: 

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?

bruno conde
Thanks Bruno, I think that's what I'll do.
mattcole