class A
{
event EventHandler Event1;
}
var mock = new Mock<A>();
How do I verify Event1 was fired? (without using manual event handlers / triggered flags)
Verifies that all verifiable expectations have been met.
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 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.
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.
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:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With