Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moq Verify events triggered

Tags:

c#

moq

class A
{
    event EventHandler Event1;
}
var mock = new Mock<A>();

How do I verify Event1 was fired? (without using manual event handlers / triggered flags)

like image 487
jameszhao00 Avatar asked Jun 16 '11 20:06

jameszhao00


People also ask

What does MOQ verify do?

Verifies that all verifiable expectations have been met.

Why does verification fail in Test 1 of MOQ?

However, that verification step no longer goes against setup A, which is now shadowed by the equivalent setup B (which however hasn't received any calls just yet). And thus verification fails in test 1. So this isn't a problem in Moq.

When to use Moq to create mock objects?

When a class has dependencies that raise events, the reaction to those events should be unit tested. To do so, the dependencies should be isolated from the code under test with the use of test doubles. One option is to use Moq to create mock objects.

How to test if an event is subscribed to a method?

So, first you have to mock the methods which you will assign the events, after you call the method which you want to test, and finally raise all subscribed events. If the event is really subscribed, you can check with Moq if the assigned method is called. GLHF! This is confusing though.

How to trigger events from an async method on a mock?

With an async method on a mock, you need to first specify that it returns a Task before you can have it trigger events. So in my example (realizing that I should have had Task Trigger (); as the method signature, this is the code I was looking for: Apparently this can be simplified even further in C# 4.6, to this:


1 Answers

I'm not sure I really understand why you ask. If you have a Mock<A>, then you control the mock so why verify that it has done something that you control?

That said, although I do use Moq's raise/raises, I still often use a flag with a lambda, which I find fairly clean:

bool eventWasDispatched = false; // yeah, it's the default
var a = new A();
a.Event1 += () => eventWasDispatched = true;
a.DoSomethingToFireEvent();
Assert.IsTrue(eventWasDispatched);
like image 87
Kaleb Pederson Avatar answered Oct 05 '22 02:10

Kaleb Pederson