为WPF项目创建单元测试

发表于:2008-9-25 16:30  作者:未知   来源:网络转载

字体: | 上一篇 | 下一篇 |我要投稿 | 推荐标签:

  为了让调用线程为STA,我们可以编写一个辅助类CrossThreadTestRunner:

以下是引用片段:
  using System;
  using System.Collections.Generic;
  using System.Text;
  using System.Threading;
  using System.Security.Permissions;
  using System.Reflection;
 
  namespace TestUnit
  {
  public class CrossThreadTestRunner
  {
  private Exception lastException;
 
  public void RunInMTA(ThreadStart userDelegate)
  {
  Run(userDelegate, ApartmentState.MTA);
  }
 
  public void RunInSTA(ThreadStart userDelegate)
  {
  Run(userDelegate, ApartmentState.STA);
  }
 
  private void Run(ThreadStart userDelegate, ApartmentState apartmentState)
  {
  lastException = null;
 
  Thread thread = new Thread(
  delegate()
  {
  try
  {
  userDelegate.Invoke();
  }
  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;
  }
  }
  }


32/3<123>

评 论

论坛新帖



建议使用IE 6.0以上浏览器,800×600以上分辨率,法律顾问:上海信义律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2022, 沪ICP备05003035号
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪公网安备 31010102002173号

51Testing官方微信

51Testing官方微博

扫一扫 测试知识全知道