Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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. } 
like image 472
stiank81 Avatar asked Feb 08 '10 08:02

stiank81


People also ask

What is the use of order attribute in NUnit?

The OrderAttribute may be placed on a test method or fixture to specify the order in which tests are run within the fixture or other suite in which they are contained. Ordering is given by the required order argument to the attribute, an int .

Can we use MOQ with NUnit?

We will install NUnit and Moq using the Nuget package manager. Make sure that in your references, NUnit and Moq are present after installation: For running NUnit tests and exploring the tests, we need to install a visual studio extension called “NUnit 3 Test Adapter”.


2 Answers

You should add the RequiresSTA attribut to your test class.

[TestFixture, RequiresSTA] public class MyTestClass { } 
like image 172
Steven Muhr Avatar answered Sep 28 '22 11:09

Steven Muhr


With more recent versions, the attribute has changed :

[Apartment(ApartmentState.STA)] public class MyTestClass {} 
like image 25
fbf Avatar answered Sep 28 '22 11:09

fbf