Search code examples
c#nunitsta

How to run unit tests in STAThread mode?


I would like to test an app that uses the Clipboard (WindowsForms) and I need the Clipboard in my unit tests also. In order to use it, it should run in STA mode, but since the NUnit TestFixture does not have a main method, I don't know where/how to annotate it.


Solution

  • For NUnit 2.2, 2.4 (See simple solution below for 2.5):

    Add an app.config file to the project containing your unit tests and include the following:

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

    You can verify that the apartment threading is STA with the following C# code:

    if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA)
    {
       throw new ThreadStateException("The current threads apartment state is not STA");
    }