Home » Blog

rounded header

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:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <sectionGroup name="NUnit">
      <section name="TestRunner" type="System.Configuration.NameValueSectionHandler" />
    </sectionGroup>
  </configSections>
 
  <NUnit>
    <TestRunner>
      <add key="ApartmentState" value="STA" />
    </TestRunner>
  </NUnit>
</configuration>

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

Data Products Visual Controls Community Store
LightSpeed ORM
NHibernate Designer
SimpleDB Tools
SharePoint Tools
WPF Elements
WPF Diagrams
Silverlight Elements
Forums
Blog
Register
Login
Subscribe to newsletter
Buy Now
My Account
Volume Discounts
Purchase Orders
Contact Us