4
votes

I have some NUnit test cases which need to be ran under STA model.

As discussed in many web sites or blogs (for example here), I added a configuration file ("app.conig") to my NUnit test assembly with the following contents.

 <?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>

To verify if a test is really ran under STA I put this test case:

 [Test]
 public void CheckSTA()
 {
    ApartmentState aptState = Thread.CurrentThread.GetApartmentState();

    Assert.IsTrue(aptState == ApartmentState.STA);
 }

This works fine if I run my unit test on NUnit console or on NUnit GUI without using a NUnit project file.

However, once I load the unit test to NUnit GUI through an NUnit project file (.nunit), the unit test starts to fail.

I've tried different config file name by following what's written on this blog (Here), but using any config file name other than "app.config" causes my unit test to fail under any circumstance.

That said, what's the right way to set this up so that my unit test is ran under STA no matter what?

3

3 Answers

10
votes

Starting with NUnit 2.5, you can use the RequiresSTAAttribute.

1
votes

Comments are often overlooked and because jnm2 gave an important hint... and obviously I can earn some bonus points if add this comment as additional answer here... ;-)

For NUnit 3.x use [Apartment(ApartmentState.STA)]

p.s. extra bonus: I fixed the link to the documentation.

0
votes

For NUnit 3.11, another solution that worked for me is to put the following attribute in AssemblyInfo:

[assembly: RequiresThread(ApartmentState.STA)]