我正在为自动映射器 map 编写测试。映射中的目标成员之一需要一个值解析器,并且该值解析器具有注入(inject)的服务依赖项。我想为解析器使用真正的实现(因为那是 map 即时测试的一部分),但我想对解析器的依赖项使用模拟。
当然,我想尽量避免在我的测试中使用 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);
}
}
}
最佳答案
这是一个解决方案,但基本上它已经完成了:
http://groups.google.com/group/automapper-users/browse_thread/thread/aea8bbe32b1f590a/f3185d30322d8109
建议是使用根据测试或实际实现设置不同的服务定位器。
关于ioc-container - 解析器的 AutoMapper 测试和依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6149736/