Note that there are some explanatory texts on larger screens.

plurals
  1. POUnit Testing an Event Firing From a Thread
    text
    copied!<p>I'm having a problem unit testing a class which fires events when a thread starts and finishes. A cut down version of the offending source is as follows:</p> <pre><code>public class ThreadRunner { private bool keepRunning; public event EventHandler Started; public event EventHandler Finished; public void StartThreadTest() { this.keepRunning = true; var thread = new Thread(new ThreadStart(this.LongRunningMethod)); thread.Start(); } public void FinishThreadTest() { this.keepRunning = false; } protected void OnStarted() { if (this.Started != null) this.Started(this, new EventArgs()); } protected void OnFinished() { if (this.Finished != null) this.Finished(this, new EventArgs()); } private void LongRunningMethod() { this.OnStarted(); while (this.keepRunning) Thread.Sleep(100); this.OnFinished(); } } </code></pre> <p>I then have a test to check that the <code>Finished</code> event fires after the <code>LongRunningMethod</code> has finished as follows:</p> <pre><code>[TestClass] public class ThreadRunnerTests { [TestMethod] public void CheckFinishedEventFiresTest() { var threadTest = new ThreadRunner(); bool finished = false; object locker = new object(); threadTest.Finished += delegate(object sender, EventArgs e) { lock (locker) { finished = true; Monitor.Pulse(locker); } }; threadTest.StartThreadTest(); threadTest.FinishThreadTest(); lock (locker) { Monitor.Wait(locker, 1000); Assert.IsTrue(finished); } } } </code></pre> <p>So the idea here being that the test will block for a maximum of one second - or until the <code>Finish</code> event is fired - before checking whether the <code>finished</code> flag is set.</p> <p>Clearly I've done something wrong as sometimes the test will pass, sometimes it won't. Debugging seems very difficult as well as the breakpoints I'd expect to be hit (the <code>OnFinished</code> method, for example) don't always seem to be.</p> <p>I'm assuming this is just my misunderstanding of the way threading works, so hopefully someone can enlighten me.</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