在 NUnit 测试中使用 WPF 组件 - 如何使用 STA? [英] Using WPF components in NUnit tests - how to use STA?

查看:67
本文介绍了在 NUnit 测试中使用 WPF 组件 - 如何使用 STA?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 NUnit 单元测试中使用一些 WPF 组件.我通过 ReSharper 运行测试,在使用 WPF 对象时失败并出现以下错误:

I need to use some WPF components in an NUnit unit test. I run the test through ReSharper, and it fails with the following error when using the WPF object:

System.InvalidOperationException:

System.InvalidOperationException:

调用线程必须是 STA,因为很多 UI 组件都需要这个.

The calling thread must be STA, because many UI components require this.

我已经阅读了有关此问题的信息,听起来该线程需要 STA,但我还没有想出如何做到这一点.触发问题的是以下代码:

I've read about this problem, and it sounds like the thread needs to be STA, but I haven't figured out how to do this yet. What triggers the problem is the following code:

[Test]
public void MyTest()
{
    var textBox = new TextBox(); 
    textBox.Text = "Some text"; // <-- This causes the exception.
}

推荐答案

你试过 这个?

... 只需为您尝试测试的 dll 创建一个 app.config 文件,并添加一些 NUnit 适当的设置以强制 NUnit 将测试环境创建为 STA 而不是 MTA.

... simply create an app.config file for the dll you are attempting to test, and add some NUnit appropriate settings to force NUnit to create the test environemnt as STA instead of MTA.

为方便起见,这里是您需要的配置文件(或将这些部分添加到您现有的配置文件中):

For convenience sake, here is the config file you would need (or add these sections to your existing config file):

<?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> 

这篇关于在 NUnit 测试中使用 WPF 组件 - 如何使用 STA?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆