Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run NUnit test in STA thread?

We are in the process of porting a WPF app to .NET Core 3, preview 5. Some NUnit tests need to run in STA threads. How can this be done?

None of the attributes like [STAThread], [RequiresSTA], ... work. This also doesn't work: [assembly: RequiresThread(ApartmentState.STA)]

The Apparent namespace does not seem to be exposed in .NET Core 3.

Has anyone done this?

like image 761
Sven Avatar asked Jun 12 '19 16:06

Sven


Video Answer


2 Answers

ApartmentAttribute was first enabled for .NET Standard 2.0 in NUnit 3.12.

First update your version of the NUnit framework, then use [Apartment(ApartmentState.STA)].

like image 142
Chris Avatar answered Nov 02 '22 19:11

Chris


In order to use STA in WPF unit testing in .Net Core 3 you need to add extension method attribute. Add this class

public class STATestMethodAttribute : TestMethodAttribute
{
    public override TestResult[] Execute(ITestMethod testMethod)
    {
        if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA)
            return Invoke(testMethod);

        TestResult[] result = null;
        var thread = new Thread(() => result = Invoke(testMethod));
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
        thread.Join();
        return result;
    }

    private TestResult[] Invoke(ITestMethod testMethod)
    {
        return new[] { testMethod.Invoke(null) };
    }
}

And then use it as

[STATestMethod]
public void TestA()
{
    // Arrange  
    var userControlA = new UserControl();

    //Act


    // Assert

}
like image 37
Stevan Avatar answered Nov 02 '22 19:11

Stevan