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

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

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

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

  红色字体部分就是实现依赖注入的代码,其他都是为了实现ITestClassCommand接口,将方法调用转发给Xunit.Sdk.TestClassCommand。

  关键问题解决,但大功还没造成,还有两个问题需要解决:

  1. 如何使用自己定义的IocTestClassCommand?

  2. 如何向IoC容器注册所依赖接口的实现?

  我们需要定义一个Attribute,继承自Xunit.RunWithAttribute,名叫IoCTestClassCommandAttribute,代码如下:

  publicclassIoCTestClassCommandAttribute:RunWithAttribute
  {
  publicIoCTestClassCommandAttribute()
  :base(typeof(IocTestClassCommand))
  {
  IBootStrapperbootStrapper=newDefaultBootStrapper();
  bootStrapper.Boot();
  }
  }

  bootStrapper.Boot是为了解决第二个问题,在其中完成IoC容器的注册。BootStrapper是一个独立的项目,ASP.NETMVC项目也是调用这个接口进行IoC容器的注册,这样实现了单元测试项目与Web项目对IoC注册的重用。

  IoCTestClassCommandAttribute在构造函数中将IocTestClassCommand的类型信息传递给父类RunWithAttribute,解决了第一个问题。

  进入激动人心的时刻。。。

  如何在测试类中使用这个特性?

  [IoCTestClassCommand]
  publicclassMyPostList
  {
  privateIBlogSiteManagementService_blogSiteService;
  publicMyPostList(IBlogSiteManagementServiceblogSiteService)
  {
  _blogSiteService=blogSiteService;
  }
  [Fact]
  publicvoidGet_My_Recent_Admin_Posts()
  {
  Assert.NotNull(_blogSiteService);
  }
  }

  只要在测试类上加上[IoCTestClassCommand]属性即可。

  运行测试:

  大功造成!只要坚持,梦想总能成现实!
33/3<123
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

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

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

沪ICP备05003035号

沪公网安备 31010102002173号