我想测试一个使用剪贴板(WindowsForms)的应用程序,我还需要在我的单元测试中使用剪贴板。为了使用它,它应该在STA模式下运行,但由于NUnit TestFixture
没有主方法,我不知道在哪里/如何对其进行注释。
我想测试一个使用剪贴板(WindowsForms)的应用程序,我还需要在我的单元测试中使用剪贴板。为了使用它,它应该在STA模式下运行,但由于NUnit TestFixture
没有主方法,我不知道在哪里/如何对其进行注释。
RequiresSTAAttribute
。[TestFixture, RequiresSTA]
或汇编级别。
[assembly:RequiresSTA]
不需要配置文件。检查: http://www.nunit.org/index.php?p=requiresSTA&r=2.5
RequiresSTA
,而 BCL 中的 STAThread
属性可以作为 RequiresSTA
的同义词。 - Alex Humphrey[RequiteSTA]
现在已经过时了,应该使用[Apartment(ApartmentState.STA)]
。 - bvj[RequiresThread(ApartmentState.STA)]
。 - FredMNUnit 3.0
最近我们迁移到了NUnit 3.0版本。我们之前使用的旧特性已经不再起作用。我们的测试中混合使用了[STAThread]
和[RequiresSTA]
,就像mas_oz2k1的回答中所述。由于它们已经过时,因此STAThread产生了编译错误,而RequiresSTA则产生了警告。
新版本似乎使用以下内容:
程序集级别
[assembly: Apartment(ApartmentState.STA)]
课程难度
[TestFixture]
[Apartment(ApartmentState.STA)]
方法级别
[Test]
[Apartment(ApartmentState.STA)]
我试图寻找这些信息,这让我走上了一条黑暗之路,在那里人们使用名为CrossThreadTestRunner的类修改他们的测试代码。我猜这是在属性类被创建之前的2004年的解决方案。
System.Threading
。 - AutomatedChaos针对 NUnit 2.2、2.4(针对 2.5,请参见下面的简单解决方案):
向包含您的单元测试的项目添加一个 app.config 文件,并包括以下内容:
<?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>
你可以使用以下C#代码验证公寓线程是STA:if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA)
{
throw new ThreadStateException("The current threads apartment state is not STA");
}
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
...