Mindscape Mindblog

Testing WPF controls in NUnit

tag icon Tagged as WPF

You can instantiate and test WPF controls in a NUnit test in the usual way:

MyTestControl control = new MyTestControl();
Assert.AreEqual(someValue, control.MyProperty);

This will appear to work wonderfully until you run it as part of your automated build, at which point it will fail on the first line, complaining that UIElements have to be created in the STA.

This happens because when you’re running the tests, you’re probably using the NUnit GUI or TestDriven.NET, which run their tests on a STA thread, but the build server is probably using the NUnit console, which runs tests on a MTA thread.

You can fix this by creating an app.config file in your test project with the following content:



  

NUnit will now run all tests in the STA, regardless of GUI or console environment. Your tests can now create UIElements and controls as required.

Leave a Reply