title: Unit testing a class used in multi-threaded WPF application
body: <p>I have written a C# class that sits in between the UI of a WPF Application and an Async Messaging System.  I am now writing Unit Tests for this class and running into problems with the dispatcher.  The following method belongs to the class I am testing and it creates a subscription handler.  So I am calling this <code>Set_Listing_Records_ResponseHandler</code> method from the Unit Test - Test Method. </p>
  
  <pre><code>public async Task&lt;bool&gt; Set_Listing_Records_ResponseHandler(
      string responseChannelSuffix, 
      Action&lt;List&lt;AIDataSetListItem&gt;&gt; successHandler, 
      Action&lt;Exception&gt; errorHandler)
  {
      // Subscribe to Query Response Channel and Wire up Handler for Query Response
      await this.ConnectAsync();
      return await this.SubscribeTo_QueryResponseChannelAsync(responseChannelSuffix, new FayeMessageHandler(delegate (FayeClient client, FayeMessage message) {
          Application.Current.Dispatcher.BeginInvoke(new Action(() =&gt;
          {
              try
              {
                  ...
              }
              catch (Exception e)
              {
                  ...
              }
          }));
      }));
  }
  </code></pre>
  
  <p>Execution flow comes back to the Application.Current.Dispatcher.... line but then throws the error:</p>
  
  <p><code>Object reference not set to an instance of an object.</code></p>
  
  <p>When I debug I can see that <code>Application.Current</code> is null.</p>
  
  <p>I have done some searching around and found a number of examples of using a dispatcher in the Unit Test - Test Method, and I have tried some of these and they prevent the error, but the code in the dispatcher is never run.</p>
  
  <p>I have not been able to find any examples where there is a Dispatcher used in the method that the Test Method is calling.</p>
  
  <p>I am working in .NET 4.5.2 on a Windows 10 machine.</p>
  
  <p>Any assistance would be greatly appreciated.</p>
  
  <p>Thanks for your time.</p>