Running WPF tests under NUnit

Our team recently began work on a new project and we're using WPF. Since we want to make our projects accessible to people who are not using VS Test Suite, we use NUnit.

The immediate problem we ran into was that NUnit could not run the tests. It threw a System.InvalidOperationException with an error message reading "The calling thread must be STA, because many UI components require this."

After searching the web, I found a blog that put me on the right track but the suggestions there didn't get the job done. By default, NUnit runs tests with ApartmentState set to MTA. In order to get NUnit to run the tests, I had to create a config file for the test project or DLL that sets ApartmentState set to STA. Trying to set it in NUnit's main config files didn't work. This is a bit of a nuisance if you do mainly WPF projects because you need a config file for each test project. It would be more convenient to be able to set it in NUnit's main config files.

Hint: NUnit's config files are case sensitive. Here's and example config file:

<?

xml version="1.0" encoding="utf-8" ?>

<

configuration>

<

configSections>

<

sectionGroup name="NUnit">

<

section name="TestRunner" type="System.Configuration.NameValueSectionHandler"/>

</

sectionGroup>

</

configSections>

<

NUnit>

<

TestRunner>

<!--

Valid values are STA,MTA. Others ignored. -->

<

add key="ApartmentState" value="STA" />

</

TestRunner>

</

NUnit>

</configuration>