Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can avoid the extra abstraction if you are willing to trade it for a small amount of view model pollution (i.e. introducing code that is only used for the sake of your tests) as follows:</p> <p>First add an optional AutoResetEvent (or ManualResetEvent) to your view model constructor and make sure that you "set" this AutoResetEvent instance when your background worker finishes the "RunWorkerCompleted" handler.</p> <pre><code>public class MyViewModel { private readonly BackgroundWorker _bgWorker; private readonly AutoResetEvent _bgWorkerWaitHandle; public MyViewModel(AutoResetEvent bgWorkerWaitHandle = null) { _bgWorkerWaitHandle = bgWorkerWaitHandle; _bgWorker = new BackgroundWorker(); _bgWorker.DoWork += (sender, e) =&gt; { //Do your work }; _bgworker.RunWorkerCompleted += (sender, e) =&gt; { //Configure view model with results if (_bgWorkerWaitHandle != null) { _bgWorkerWaitHandle.Set(); } }; _bgWorker.RunWorkerAsync(); } } </code></pre> <p>Now you can pass in an instance as part of your unit test.</p> <pre><code>[Test] public void Can_Create_View_Model() { var bgWorkerWaitHandle = new AutoResetEvent(false); //Make sure it starts off non-signaled var viewModel = new MyViewModel(bgWorkerWaitHandle); var didReceiveSignal = bgWorkerWaitHandle.WaitOne(TimeSpan.FromSeconds(5)); Assert.IsTrue(didReceiveSignal, "The test timed out waiting for the background worker to complete."); //Any other test assertions } </code></pre> <p>This is precisely what the AutoResetEvent (and ManualResetEvent) classes were designed for. So aside from the slight view model code pollution, I think this solution is quite neat.</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