如何在STAThread模式下运行unit testing?

我想testing一个使用剪贴板(WindowsForms)的应用程序,我也需要我的Unittests中的剪贴板。 为了使用它,它应该在STA模式下运行,但由于NUnit Testfixture没有主要的方法,我不知道在哪里/如何注释它…

谢谢!

对于NUnit 2.2,2.4(请参阅下面的2.5简单解决scheme):

将app.config文件添加到包含unit testing的项目中,并包含以下内容:

<?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#代码validation公寓线程是否为STA:

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

如果您使用nunit 2.5+,则可以在课堂上使用新的RequiresSTAAttribute

 [TestFixture, RequiresSTA] 

或assembly水平。

 [assembly:RequiresSTA] 

不需要configuration文件。 检查: http : //www.nunit.org/index.php?p= requiresSTA& r=2.5

NUnit 3.0

我们最近迁移到NUnit 3.0,我们已经使用的旧属性不再有效。 我们的testing使用了[STAThread][RequiresSTA]的混合,就像上面mas_oz2k1的回答一样。 STAThread由于不再被发现而给出了编译错误,RequiresSTA正在给出警告,因为它已被弃用。

新政似乎使用以下内容:

assembly水平

 [assembly: Apartment(ApartmentState.STA)] 

课堂级别

 [TestFixture] [Apartment(ApartmentState.STA)] 

方法级别

 [Test] [Apartment(ApartmentState.STA)] 

试图find这些信息让我走了一条黑暗的道路,人们正在使用一个名为CrossThreadTestRunner的类来修改他们的testing代码。 这是2004年我假设的解决scheme,在这些属性类创build之前。

在NUnit 2.6.1+中,您可以使用/ apartment = 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 ...