Note that there are some explanatory texts on larger screens.

plurals
  1. POC# and Moq - How to Assert an Event is Not Raised
    text
    copied!<p>I have an application that raises events depending on the state of a Sim object. In particular, if the state of the Sim changes - i.e. from PinRequired to Accessible - an OnStatus event will be raised. The events notify listeners on a new thread.</p> <p>I am using Moq in my unit tests and am able to assert that OnStatus is raised like so:</p> <pre><code> [Test] public void TestOnStatusIsRaised() { Sim sim = new Sim(); sim.OnStatus += OnStatus; lock (this) { sim.UpdateSimInfo(new Info("a new status")); Monitor.Wait(this); } Assert.IsTrue(_onStatusCalled); } private void OnStatus(SimStatus obj) { lock (this) { _onStatusCalled = true; Monitor.Pulse(this); } } </code></pre> <p>As you can see, using the Monitor class I can wait until the event is raised before proceeding and asserting that the _onStatusCalled flag has been set to true.</p> <p>My difficulty arises when I want to assert that an event is not raised. I can't use Monitor to wait for the event not to be raised as the test would wait forever! I could added a timeout to the wait, but that seems like a dirty hack.</p> <p>I have tried the following:</p> <pre><code> [Test] public void TestOnStatusIsNotFired() { Sim sim = new Sim(); sim.OnStatus += onStatus =&gt; Assert.Fail("OnStatus Was called"); sim.UpdateSimInfo(new Info("the same status")); } </code></pre> <p>but it doesn't work - before fixing the code to ensure the event is not raised, the test always passes. I have even stepped through the code and observed an exception being thrown by the <code>Assert.Fail()</code>, but this does not cause the test to fail as my event is raised in a try/catch block and the NUnit exception is caught.</p> <p>Any ideas?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload