【问题标题】:AutoMapper testing and dependency injection for resolvers解析器的 AutoMapper 测试和依赖注入
【发布时间】:2011-05-27 08:35:13
【问题描述】:

我正在为自动映射器地图编写测试。映射中的目标成员之一需要一个值解析器,并且该值解析器具有注入的服务依赖项。我想为解析器使用真正的实现(因为那是地图即时测试的一部分),但我想对解析器的依赖项使用模拟。

当然,我想尽量避免在我的测试中使用 ioc 容器,但是如何在没有 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);
            }
        }
    }

【问题讨论】:

    标签: ioc-container automapper


    【解决方案1】:

    这是一个解决方案,但基本上它已经完成了:

    http://groups.google.com/group/automapper-users/browse_thread/thread/aea8bbe32b1f590a/f3185d30322d8109

    建议使用根据测试或实际实现设置不同的服务定位器。

    【讨论】:

      最近更新 更多