Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with runnig NUnit tests under STA

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?

like image 620
Kei Avatar asked Dec 22 '22 09:12

Kei


2 Answers

Starting with NUnit 2.5, you can use the RequiresSTAAttribute.

like image 79
Daniel Avatar answered Jan 04 '23 23:01

Daniel


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.

like image 25
Beachwalker Avatar answered Jan 04 '23 21:01

Beachwalker