题
我想测试使用剪贴板(WindowsForms)一个应用程序,我需要剪贴板在我的单元测试也。为了使用它,它应该在STA模式下运行,但由于NUnit的TestFixture
没有一个主要的方法,我不知道在哪里/如何注释它。
解决方案
有关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>
可以验证单元线程是STA与下面的C#代码:
if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA)
{
throw new ThreadStateException("The current threads apartment state is not STA");
}
其他提示
如果您使用NUnit 2.5+,可以在类中使用新的RequiresSTAAttribute
[TestFixture, RequiresSTA]
或组件的水平。
[assembly:RequiresSTA]
没有必要的配置文件。校验: http://www.nunit.org/index.php?p=requiresSTA&r=2.5
<强> NUnit的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年溶液I假设,已创建了这些属性类之前。
在NUnit的2.6.1+可以使用的 /公寓= 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
...
不隶属于 StackOverflow