如何在STA线程中运行NUnit测试?

时间:2019-06-12 16:56:20

标签: c# .net-core nunit sta

我们正在将WPF应用程序移植到.NET Core 3,预览版5。 一些NUnit测试需要在STA线程中运行。该怎么办?

[STAThread],[RequiresSTA]等属性都不起作用。 这也行不通:[assembly:RequiresThread(ApartmentState.STA)]

.NET Core 3中似乎没有公开表观命名空间。

有人这样做吗?

2 个答案:

答案 0 :(得分:1)

ApartmentAttribute首次在NUnit 3.12中启用了.NET Standard 2.0。

首先更新您的NUnit框架版本,然后使用[Apartment(ApartmentState.STA)]

答案 1 :(得分:1)

为了在.Net Core 3中的WPF单元测试中使用STA,您需要添加扩展方法属性。 添加此类

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) };
    }
}

然后将其用作

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

    //Act


    // Assert

}
相关问题