sti*_*k81 43 c# wpf resharper nunit unit-testing
我需要在NUnit单元测试中使用一些WPF组件.我通过ReSharper运行测试,并在使用WPF对象时失败并出现以下错误:
System.InvalidOperationException:
调用线程必须是STA,因为许多UI组件都需要这个.
我已经读过这个问题了,听起来这个线程需要是STA,但我还没想出如何做到这一点.触发此问题的原因是以下代码:
[Test]
public void MyTest()
{
var textBox = new TextBox();
textBox.Text = "Some text"; // <-- This causes the exception.
}
Run Code Online (Sandbox Code Playgroud)
Ste*_*uhr 65
您应该将RequiresSTA attribut 添加到您的测试类.
[TestFixture, RequiresSTA]
public class MyTestClass
{
}
Run Code Online (Sandbox Code Playgroud)
小智 46
对于更新的版本,该属性已更改:
[Apartment(ApartmentState.STA)]
public class MyTestClass
{}
Run Code Online (Sandbox Code Playgroud)
你试过这个吗?
...只需为您尝试测试的 dll 创建一个 app.config 文件,并添加一些 NUnit 适当的设置以强制 NUnit 将测试环境创建为 STA 而不是 MTA。
为了方便起见,这里是您需要的配置文件(或将这些部分添加到现有的配置文件中):
<?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>
Run Code Online (Sandbox Code Playgroud)