Is there a way to .DoNothing() on an Event?

2 posts, 0 answers
  1. Steve
    Steve avatar
    13 posts
    Member since:
    Feb 2013

    Posted 21 Jan 2014 Link to this post

    I asked this question on Stack Overflow initially, but I will come to the forums as SO is getting pretty noisy these days.

    http://stackoverflow.com/questions/21268065/trying-to-unit-test-an-event-with-justmock (has example code)

    Basically, all I want to do is be able to say '.DoNothing()' on an event.   Is this possible?  Is my syntax just bad?  Any tricks to get around it?

    Thanks,
    -Steve
  2. Stefan
    Admin
    Stefan avatar
    198 posts

    Posted 22 Jan 2014 Link to this post

    Hello Steve,

    I replied to your question on SO. I'm also posting the answer here.

    It's impossible to mock the delegate invocation itself, since it's implemented internally by the JIT.

    You have several alternative options. If you raise the event in a method dedicated for that purpose (as in your sample), then you can simply mock that method instead. So, in your sample that becomes:

        Mock.Arrange(() => s.FireEvent()).DoNothing();

    If that's not possible then you can mock the method that adds handlers to the event (the one called when Sample += ... is invoked). You can do this like so:

     
    var mock = Mock.Create<Sample>(); // we need this just for the following arrangement
    Mock.ArrangeSet(() => mock.TheEvent += null).IgnoreInstance().IgnoreArguments().DoNothing();
     
    var real = new Sample(); // TheEvent += CallMe will now do nothing
    real.FireEvent(); // TheEvent is empty<br><br>

    Finally, as a third option, you can remove all handlers from the event using reflection at some point where you know the event is just about to be fired, or that no one else will attach to it:

    new PrivateAccessor(real).SetField("TheEvent", null);
    real.FireEvent(); // TheEvent is null right now

    Caveat: this last option is dependent on the compiler implementation. It will work for event declarations in C# code, but will not work for VB events.

    Regards,
    Stefan
    Telerik
    Share what you think about JustTrace & JustMock with us, so we can become even better! You can use the built-in feedback tool inside JustTrace, our forums, or our JustTrace or JustMock portals.
  3. DevCraft R3 2016 release webinar banner
Back to Top