梦想成现实:用xUnit.net在单元测试中实现构造函数依赖注入

发表于:2011-8-09 10:40

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:dudu    来源:51Testing软件测试网采编

  method.CreateInstance()实际调用的代码是这样的:

  publicobjectCreateInstance()
  {
  returnActivator.CreateInstance(method.ReflectedType);
  }

  一看代码就知道为什么只支持无参的构造函数。

  看到瓜,就容易找到解决方法,既然在testClass==null时才会创建测试类的实例,如果我们通过IoC容器在这个方法执行前创建testClass的实例并传递LifetimeCommand.Execute方法,不就可以解决问题了吗?

  所以,继续顺藤摸瓜,找出在哪里调用了LifetimeCommand.Execute(objecttestClass)方法。。。

  在Xunit.Sdk.TestClassCommandRunner.Execute()中找到:

  MethodResultmethodResult=command.Execute(testClassCommand.ObjectUnderTest:;

  testClassCommand的类型是ITestClassCommand接口,该接口的实现是Xunit.Sdk.TestClassCommand,看看它的ObjectUnderTest属性:

public object ObjectUnderTest
{   
get { return null; }
}

  只要这里从IoC容器返回测试类的实例,就可以实现依赖注入了。

  进入解决方案...

  注:解决方案不需要修改任何xUnit.net的源代码。

  在单元测试项目中创建一个实现ITestClassCommand接口的IocTestClassCommand类,代码如下:

  publicclassIocTestClassCommand:ITestClassCommand
  {
  TestClassCommand_testClassCommand;
  publicIocTestClassCommand()
  :this((ITypeInfo)null){
  }
  publicIocTestClassCommand(TypetypeUnderTest)
  :this(Reflector.Wrap(typeUnderTest)){
  }
  publicIocTestClassCommand(ITypeInfotypeUnderTest)
  {
  _testClassCommand=newTestClassCommand(typeUnderTest);
  }
  publicobjectObjectUnderTest
  {
  get{returnIoCFactory.Instance.CurrentContainter.
  Resolve(_testClassCommand.TypeUnderTest.Type);}
  }
  publicRandomRandomizer
  {
  get{return_testClassCommand.Randomizer;}
  set{_testClassCommand.Randomizer=value;}
  }
  publicITypeInfoTypeUnderTest
  {
  get{return_testClassCommand.TypeUnderTest;}
  set{_testClassCommand.TypeUnderTest=value;}
  }
  [SuppressMessage(“Microsoft.Design”,“CA1062:Validateargumentsofpublicmethods”,
  MessageId=“0”,Justification=“Thisparameterisverifiedelsewhere.”)]
  publicintChooseNextTest(ICollection<IMethodInfo>testsLeftToRun)
  {
  return_testClassCommand.Randomizer.Next(testsLeftToRun.Count);
  }
  publicExceptionClassFinish()
  {
  return_testClassCommand.ClassFinish();
  }
  publicExceptionClassStart()
  {
  return_testClassCommand.ClassStart();
  }
  publicIEnumerable<ITestCommand>EnumerateTestCommands(IMethodInfotestMethod)
  {
  return_testClassCommand.EnumerateTestCommands(testMethod);
  }
  publicIEnumerable<IMethodInfo>EnumerateTestMethods()
  {
  return_testClassCommand.EnumerateTestMethods();}publicboolIsTestMethod(IMethodInfotestMethod)
  {
  return_testClassCommand.IsTestMethod(testMethod);
  }
  }

32/3<123>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号