ISerialized .Net, C#, Scrum and agile software development

23Mar/100

Running NUnit in an STA thread

While unit testing a WPF Caliburn application, I bumped into the following error:

The calling thread must be STA

and I ended up with a cross-thread exception. When diving into this problem I found that TestDriver.Net actually runs in STA (acronym for Singel Thread Apartment) by default, but  NUnit is not! It is however a fairly simple configuration change to get NUnit running in STA.  Add or update your app.config in your test project with following:

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

As this is located in the test projects app.config file, your NUnit tests will now run in STA. 

Posted by Pål Eie