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 Set_Listing_Records_ResponseHandler method from the Unit Test - Test Method.
public async Task<bool> Set_Listing_Records_ResponseHandler(
string responseChannelSuffix,
Action<List<AIDataSetListItem>> successHandler,
Action<Exception> 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(() =>
{
try
{
...
}
catch (Exception e)
{
...
}
}));
}));
}
Execution flow comes back to the Application.Current.Dispatcher.... line but then throws the error:
Object reference not set to an instance of an object.
When I debug I can see that Application.Current is null.
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.
I have not been able to find any examples where there is a Dispatcher used in the method that the Test Method is calling.
I am working in .NET 4.5.2 on a Windows 10 machine.
Any assistance would be greatly appreciated.
Thanks for your time.
Thanks to all who responded, your feedback was much appreciated.
Here is what I ended up doing:
I created a private variable in my UICommsManager class:
and initialized this in the constructor of the UICommsManager. I then updated my message handlers to use the new _MessageHandlerContext instead of the Dispatcher:
When used from the UI the UICommsManager class gets
SynchronizationContext.Currentpassed into the constructor.I updated my Unit Test to add the following private variable:
And the following method which initializes it:
And then the UICommsManager gets the _Context variable passed into it's constructor from the Test Method.
Now it works in both scenarios, when called by WPF, and when called by Unit Test.