Hello
We have a big project in WPF C#.
We have some legacy code that can't be refactored in such a way that we can run "normal" tests.
The test we can build at this point need to run in STA Thread.
Our tests runs perfectly with mstest but not with NCrunch.
On MSTest we customize the attribute and use the following classes.
Is there a solution for this problem?
Thank you
public class STATestClassAttribute : TestClassAttribute
{
public override TestMethodAttribute GetTestMethodAttribute(TestMethodAttribute testMethodAttribute)
{
if (testMethodAttribute is STATestMethodAttribute)
return testMethodAttribute;
return new STATestMethodAttribute(base.GetTestMethodAttribute(testMethodAttribute));
}
}
public class STATestMethodAttribute : TestMethodAttribute
{
private readonly TestMethodAttribute _testMethodAttribute;
public STATestMethodAttribute()
{
}
public STATestMethodAttribute(TestMethodAttribute testMethodAttribute)
{
_testMethodAttribute = 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)
{
if (_testMethodAttribute != null)
return _testMethodAttribute.Execute(testMethod);
return new[] { testMethod.Invoke(null) };
}
}
The error message in ncrunch:
System.InvalidOperationException: The calling thread must be STA, because many UI components require this.
at System.Windows.Input.InputManager..ctor()
at System.Windows.Input.InputManager.GetCurrentInputManagerImpl()
at System.Windows.Input.InputManager.get_Current()
at System.Windows.Input.KeyboardNavigation..ctor()
at System.Windows.FrameworkElement.FrameworkServices..ctor()
at System.Windows.FrameworkElement.EnsureFrameworkServices()
at System.Windows.FrameworkElement..ctor()
at System.Windows.Controls.Panel..ctor()
at System.Windows.Controls.Canvas..ctor()
Edited 08 Jun 2022 11:58 UTC