Mat*_*teS 6 ioc-container automapper
我正在为自动映射器地图编写测试。映射中的目标成员之一需要一个值解析器,并且该值解析器具有注入的服务依赖项。我想为解析器使用真正的实现(因为那是map im测试的一部分),但我想对解析器具有的依赖项使用模拟。
当然,我想避免在测试中使用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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是一种解决方案,但基本上是 iv 已经完成的:
建议使用服务定位器,该定位器根据测试或实际实施而设置不同。
| 归档时间: |
|
| 查看次数: |
1883 次 |
| 最近记录: |