我有一些需要在 STA 模型下运行的 NUnit 测试用例。
正如许多网站或博客(例如 here)中所讨论的那样,我向我的 NUnit 测试程序集添加了一个配置文件(“app.conig”),内容如下。
<?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 下运行,我放置了这个测试用例:
[Test]
public void CheckSTA()
{
ApartmentState aptState = Thread.CurrentThread.GetApartmentState();
Assert.IsTrue(aptState == ApartmentState.STA);
}
如果我在 NUnit 控制台或 NUnit GUI 上不使用 NUnit 项目文件运行我的单元测试,这会正常工作。
但是,一旦我通过 NUnit 项目文件 (.nunit) 将单元测试加载到 NUnit GUI,单元测试就会开始失败。
我已按照此博客 (Here) 上的内容尝试了不同的配置文件名,但使用“app.config”以外的任何配置文件名都会导致我的单元测试在任何情况下都失败。
也就是说,正确的设置方法是什么,以便我的单元测试无论如何都在 STA 下运行?
最佳答案
从 NUnit 2.5 开始,您可以使用 RequiresSTAAttribute。
关于c# - 在 STA 下运行 NUnit 测试的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1256329/