Using WPF components in NUnit tests - how to use STA?

泪湿孤枕 提交于 2019-12-20 09:47:11

问题


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:

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

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.
}

回答1:


Have you tried this?


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



回答2:


You should add the RequiresSTA attribut to your test class.

[TestFixture, RequiresSTA]
public class MyTestClass
{
}



回答3:


With more recent versions, the attribute has changed :

[Apartment(ApartmentState.STA)]
public class MyTestClass
{}


来源:https://stackoverflow.com/questions/2220418/using-wpf-components-in-nunit-tests-how-to-use-sta

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!