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>
Comments
Anonymous comments are disabled
About John D'Addamio
I am a Software Design Engineer in Test (SDET) on the Developer Aftermarket Solutions team at Microsoft Corporation. Basically, an SDET is a programmer who specializes in testing other people’s software and/or writing software that is used for testing. I joined Microsoft in 2003 and the Solutions team in 2005. Prior to joining Microsoft, I was a developer and developer lead writing real time software; mostly air traffic control systems. The fun thing about testing is that people are happy when you find a way to break things!
I like to balance my high tech work life with low tech activities. So, outside of work, you will probably find me on the back of a horse, doing the maintenance that horses require, or reading a book.