如何运行STAThread模式的单元测试? [英] How to run unit tests in STAThread mode?
问题描述
我想测试使用剪贴板(WindowsForms)的应用程序,我需要在我的单元测试也剪贴板。为了使用它,它应该STA模式下运行,但由于NUnit的的TestFixture没有一个主要的方法,我不知道在哪里/如何诠释它...
I would like to test an app that uses the Clipboard (WindowsForms) and I need the Clipboard in my Unittests 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...
谢谢!
推荐答案
有关NUnit的2.2,2.4(见下文2.5简单的解决方案):
For NUnit 2.2, 2.4 (See simple solution below for 2.5):
添加一个app.config文件添加到项目包含您的单元测试,包括以下内容:
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>
您可以验证单元线程是STA与下面的C#code:
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");
}
这篇关于如何运行STAThread模式的单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!