Getting Your NUnit Tests to Run as STA

As a follow-up to my recent post on my Winforms Automation Extensisons post, I realized that I forgot to mention a very important detail.

In many cases, WinForms require to be executed in a Single Threaded Apartment (STA). I write all of my tests in the TestDriven.NET test runner, which runs in the STA by default, but NUnit does not. Resharper also uses the NUnit test runner, so it also runs in MTA by default.

To tell NUnit to run in the STA (and therefore, Resharper), you need to add some data to your app.config file. If you do not already have one, create a file in your test assembly called app.config. Add the following XML:

   1: <?xml version="1.0" encoding="utf-8" ?>
   2: <configuration>
   3:   <configSections>
   4:     <sectionGroup name="NUnit">
   5:       <section name="TestRunner" type="System.Configuration.NameValueSectionHandler"/>
   6:     </sectionGroup>
   7:   </configSections>
   8:   <NUnit>
   9:     <TestRunner>
  10:       <add key="ApartmentState" value="STA" />
  11:     </TestRunner>
  12:   </NUnit>
  13: </configuration>

Presto! Tests will run in the STA from now on.

Leave a Reply