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. }
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 .
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”.
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 {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With