我正在为一个automapper地图编写一个测试.映射中的一个目标成员需要值解析器,并且该值解析器具有注入的服务依赖性.我想使用解析器的真实实现(因为这是地图测试的一部分)但是我喜欢
当然,我想在我的测试中尽量避免使用ioc容器,但是如何在没有测试的情况下轻松解决我的值解析器的依赖关系?
这是我相当简化的例子,在实际情况下有几个解析器有时有很多依赖,我真的不喜欢在我的测试中基本实现我自己的依赖解析器.我应该使用轻量级的ioc容器吗?
[TestFixture] public class MapperTest { private IMyService myService; [SetUp] public void Setup() { Mapper.Initialize(config => { config.ConstructServicesUsing(Resolve); config.AddProfile<MyProfile>(); }); } public T Resolve<T>() { return (T) Resolve(typeof (T)); } public object Resolve(Type type) { if (type == typeof(MyValueResolver)) return new MyValueResolver(Resolve<IMyService>()); if (type == typeof(IMyService)) return myService; Assert.Fail("Can not resolve type " + type.AssemblyQualifiedName); return null; } [Test] public void ShouldConfigureCorrectly() { Mapper.AssertConfigurationIsValid(); } [Test] public void ShouldMapStuff() { var source = new Source() {...}; var child = new Child(); myService = MockRepository.GenerateMock<IMyService>(); myService .Stub(x => x.DoServiceStuff(source)).Return(child); var result = Mapper.Map<ISource, Destination>(source); result.Should().Not.Be.Null(); result.Child.Should().Be.SameInstanceAs(child); } } public class MyProfile : Profile { protected override void Configure() { base.Configure(); CreateMap<ISource, Destination>() .ForMember(m => m.Child, c => c.ResolveUsing<MyResolver>()); } } public class MyResolver: ValueResolver<ISource, Destination> { private readonly IMyService _myService; public MyResolver(IMyService myService) { _myService = myService; } protected override Child ResolveCore(ISource source) { return _myService.DoServiceStuff(source); } } }这是一个解决方案,但基本上它已经完成了iv:
http://groups.google.com/group/automapper-users/browse_thread/thread/aea8bbe32b1f590a/f3185d30322d8109
建议使用服务定位器,根据测试或实际实现,设置不同.