How to run unit tests in STAThread mode?

微笑、不失礼 提交于 2019-11-28 06:09:32
Bernhard Hofmann

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

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

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.

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
...
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!