This is a migrated thread and some comments may be shown as answers.

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

1 Answer 104 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
Steve
Top achievements
Rank 1
Steve asked on 21 Jan 2014, 09:30 PM
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

1 Answer, 1 is accepted

Sort by
0
Stefan
Telerik team
answered on 22 Jan 2014, 09:26 AM
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.
Tags
General Discussions
Asked by
Steve
Top achievements
Rank 1
Answers by
Stefan
Telerik team
Share this question
or