1

I am trying to get the event handler without doing any changes in MyControl class. I tried to use reflection but I am not able to get the handler. Following is a code sample. Thanks

public class MyControl : Control
{
    public void Register()
    {
        SizeChanged += MyControl_SizeChanged;
    }

    void MyControl_SizeChanged(object sender, EventArgs e)
    {
        // Do something
    }
}

//[TestFixture]
public class MyControlTest
{
    //  [Test]
    public void RegisterTest()
    {

        var control = new MyControl();
        control.Register();

        var eventInfo = control.GetType().GetEvent("SizeChanged", BindingFlags.Public | BindingFlags.Instance);

        // Need to get the handler (delegate) and GetInvocationList().Count
        EventHandler handler = ...;

        var count = handler.GetInvocationList().Count();
        Assert.That(count, IsolationLevel.EqualTo(1));
    }
}
ehh
  • 3,412
  • 7
  • 43
  • 91

2 Answers2

1

Events don't actually have handlers; an event is just a pair of specially-named add & remove methods.
For more information, see my blog.

How the event stores its handlers is an implementation detail; WinForms controls use an EventHandlerList.
You can see this in the source.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • But how it helps me to get to the GetInvocationList() method if I do not have the handler? Or let say, how can I use reflection to get the EventHandler?\ – ehh Aug 12 '15 at 15:23
  • @ehh: You can use lots of reflection to get the protected HandlerList and the private key object. However, you probably shouldn't be doing this. – SLaks Aug 12 '15 at 15:25
  • so how can I achieve this test, I need to ensure that Register method is covered by RegisterTest unit test. – ehh Aug 12 '15 at 15:28
0

That's probably because of it's protection level which is currently private as can be seen from your posted code

void MyControl_SizeChanged(object sender, EventArgs e)
{
    // Do something
}
Rahul
  • 76,197
  • 13
  • 71
  • 125