2
我正在編寫一個自動映射器映射的測試。映射中的一個目標成員需要一個值解析器,並且該值解析器具有注入的服務依賴關係。我想使用解析器的真正實現(因爲那是地圖im測試的一部分),但是我喜歡使用模擬器來解析器所具有的依賴關係。解析器的AutoMapper測試和依賴注入
Ofcourse我想盡量避免在我的測試中使用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);
}
}
}