我们正在将一个WPF应用程序移植到.NET Core 3,预览5。 一些NUnit测试需要在STA线程中运行。如何做到这一点?
像[STAThread]、[RequiresSTA]等属性都不起作用。 这也不起作用:[assembly: RequiresThread(ApartmentState.STA)]
在.NET Core 3中似乎没有暴露Apparent命名空间。
有人做过这个吗?
我们正在将一个WPF应用程序移植到.NET Core 3,预览5。 一些NUnit测试需要在STA线程中运行。如何做到这一点?
像[STAThread]、[RequiresSTA]等属性都不起作用。 这也不起作用:[assembly: RequiresThread(ApartmentState.STA)]
在.NET Core 3中似乎没有暴露Apparent命名空间。
有人做过这个吗?
ApartmentAttribute
在NUnit 3.12中首次支持.NET Standard 2.0。
请先更新您的NUnit框架版本,然后使用[Apartment(ApartmentState.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
}
using NUnit.Framework;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.Framework.Internal.Commands;
namespace NunitExtensions;
/// <summary>
/// This attribute forces the test to execute in an STA Thread.
/// Needed for UI testing.
/// The NUnit <see cref="NUnit.Framework.ApartmentAttribute"/> does not seem to work on .Net 6....
/// </summary>
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public class UITestAttribute : NUnitAttribute, IWrapTestMethod
{
public TestCommand Wrap(TestCommand command)
{
return Thread.CurrentThread.GetApartmentState() == ApartmentState.STA
? command
: new StaTestCommand(command);
}
private class StaTestCommand : TestCommand
{
private readonly TestCommand _command;
public StaTestCommand(TestCommand command) : base(command.Test)
{
_command = command;
}
public override TestResult Execute(TestExecutionContext context)
{
TestResult? result = null;
var thread = new Thread(() => result = _command.Execute(context));
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
return result ?? throw new Exception("Failed to run test in STA!");
}
}
}