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

stiank81 picture stiank81 · Feb 8, 2010 · Viewed 11.7k times · Source

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

Answer

Steven Muhr picture Steven Muhr · Jun 4, 2013

You should add the RequiresSTA attribut to your test class.

[TestFixture, RequiresSTA]
public class MyTestClass
{
}