}
catch (Exception e)
{
lastException = e;
}
});
thread.SetApartmentState(apartmentState);
thread.Start();
thread.Join();
if (ExceptionWasThrown())
ThrowExceptionPreservingStack(lastException);
}
private bool ExceptionWasThrown()
{
return lastException != null;
}
[ReflectionPermission(SecurityAction.Demand)]
private static void ThrowExceptionPreservingStack(Exception exception)
{
FieldInfo remoteStackTraceString = typeof(Exception).GetField(
"_remoteStackTraceString",
BindingFlags.Instance | BindingFlags.NonPublic);
remoteStackTraceString.SetValue(exception, exception.StackTrace + Environment.NewLine);
throw exception;
}
}
}
并编写正确的测试代码: 软件测试
以下是引用片段:
[TestFixture] public class ClassTest { [Test] public void TestRun() { CrossThreadTestRunner runner = new CrossThreadTestRunner(); runner.RunInSTA( delegate { Console.WriteLine(Thread.CurrentThread.GetApartmentState()); WindowsApplication1.Window1 obj = new WindowsApplication1.Window1(); double expected = 9; double result = obj.GetSomeValue(3); Assert.AreEqual(expected, result); }); } }
另外,使用NUnit时,您需要添加对nunit.framework.dll的引用,并对测试类添加[TestFixture]属性标记以及对测试方法添加[Test]属性标记,然后将生成的程序集用nunit.exe打开就可以了,关于NUnit的具体用法您可以参考其官方文档。
文章来源于领测软件测试网 https://www.ltesting.net/