Search code examples
c#wpfunit-testingdispatcher

Creating a System.Windows.Controls.Image throws an exception - how do I use the dispatcher to instantiate it?


I'm running my unit tests on a piece of code that does the following in the test:

Assert.IsNotNull(target.Icon);

Inside the getter for the Icon property, I'm doing this:

System.Windows.Controls.Image img = new System.Windows.Controls.Image();

That's throwing this exception: System.InvalidOperationException : The calling thread must be STA, because many UI components require this.

I understand what that means, and I understand that I need to use the Dispatcher, but I'm a bit confused about how or why... this is a property of my ViewModel and I don't get any of these exceptions when running the application.

Other info: this only started failing when I upgraded to .NET 4.


Solution

  • The problem here is that you are unit testing WPF which requires an STA to run properly but the unit testing framework is using an MTA. You need to setup your unit testing framework to run your tests in an STA.

    Each framework has a different way of doing it. Usually you can find it by just typing the testing framework name and STA into google.