开发者

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

开发者 https://www.devze.com 2022-12-19 17:40 出处:网络
I need to use some WPF components in an NUnit unit test. I run the test through Re开发者_Go百科Sharper, and it fails with the following error when using the WPF object:

I need to use some WPF components in an NUnit unit test. I run the test through Re开发者_Go百科Sharper, 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.
}


You should add the RequiresSTA attribut to your test class.

[TestFixture, RequiresSTA]
public class MyTestClass
{
}


With more recent versions, the attribute has changed :

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


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

精彩评论

暂无评论...
验证码 换一张
取 消