How to run unit tests in STAThread mode?

2019-01-17 05:38发布

问题:

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.

回答1:

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");
}


回答2:

If you are using nunit 2.5+, you can use the new The RequiresSTAAttribute at class

[TestFixture, RequiresSTA]

or assembly level.

[assembly:RequiresSTA]

No need for config file. check: http://www.nunit.org/index.php?p=requiresSTA&r=2.5



回答3:

NUnit 3.0

We migrated to NUnit 3.0 recently and the old attributes that we had been using no longer worked. Our tests used a mixture of [STAThread] and [RequiresSTA] as in mas_oz2k1's answer above. STAThread was giving compile errors since it was no longer found and RequiresSTA was giving warnings because it has been deprecated.

The New Deal appears to be using the following:

Assembly Level

[assembly: Apartment(ApartmentState.STA)]

Class Level

[TestFixture]
[Apartment(ApartmentState.STA)]

Method Level

[Test]
[Apartment(ApartmentState.STA)]

Trying to find this information took me down a dark road where people were modifying their test code using a class called CrossThreadTestRunner. This was the solution in 2004 I assume, before these attribute classes were created.



回答4:

In NUnit 2.6.1+ you can use the /apartment=STA command line flag:

NUnit-Console version 2.6.3.13283
Copyright (C) 2002-2012 Charlie Poole.
Copyright (C) 2002-2004 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov.
Copyright (C) 2000-2002 Philip Craig.
All Rights Reserved.

Runtime Environment -
   OS Version: Microsoft Windows NT 6.1.7601 Service Pack 1
  CLR Version: 4.0.30319.18052 ( Net 4.5 )


NUNIT-CONSOLE [inputfiles] [options]

Runs a set of NUnit tests from the console.

You may specify one or more assemblies or a single
project file of type .nunit.

Options:
...
/apartment=X            Apartment for running tests: MTA (Default), STA
...


标签: c# nunit sta