红色字体部分就是实现依赖注入的代码,其他都是为了实现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]属性即可。
运行测试:
大功造成!只要坚持,梦想总能成现实!