繁体   English   中英

如何在STAThread模式下运行单元测试?

[英]How to run unit tests in STAThread mode?

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

如果您使用的是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年我假设的解决方案,在创建这些属性类之前。

对于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 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
...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM