【问题标题】:Assigning IMappingEngine in constructor causes mapping exception when mapping only when running from unit test仅在从单元测试运行映射时,在构造函数中分配 IMappingEngine 会导致映射异常
【发布时间】:2015-09-29 12:43:51
【问题描述】:

我有一个单元测试 - 我在设置中执行 AutoMapperConfiguration。然后,我在我实际进行映射的类的构造函数中将 IMappingEngine 设置为私有属性。如果我使用此属性,单元测试将失败,但使用 automapper 中的静态方法可以正常工作。运行实际程序时,这两种方法都可以正常工作。我能看到的唯一区别是单元测试在单独的程序集中。 CLS 合规性已打开。

public class AutomapperConfiguration
{
    public static void Configure()
    {
        Mapper.Initialize(cfg =>
        {
            cfg.AddProfile<AclassMappingProfile>();
        });
    }
    public static void Reset()
    {
        Mapper.Reset();
    }
}
public class AssetModelFactoryTests
{
    [SetUp]
    public void SetUp()
    {
        AutomapperConfiguration.Configure();
    }
    [Test]
    public void TestA()
    {
        var a = new A();
    }
}

public class A
{
    private IMappingEngine _mappingEngine;
    public A()
    {
         _mappingEngine = Mapper.Engine;
    }

    public void DoA()
    {
         Mapper.Map<Destination>(source); //works
         _mappingEngine.Map<Destionation>(source); //Throws mapping not supported
    }
}

【问题讨论】:

  • 当测试失败时,您从测试中得到什么异常?

标签: c# .net unit-testing automapper cls-compliant


【解决方案1】:

如果您打算测试这些方法,请不要使用静态 Mapper.* 方法。在任何地方使用IMappingEngine,在应用程序启动时配置它并通过适当的依赖反转机制注入。

【讨论】:

  • 我有一个用于 Unity DI 的 nuget 包来自动化它,并计划为 Autofac 编写相同的包。
  • 我知道,我使用 IMappingEngine 和静态 Mapper.Engine 的原因是因为它(一如既往)是更大更旧系统的一部分。我想这样做是为了以后在我们重构更多代码时更容易通过 DI 添加 IMappingEngine。
猜你喜欢
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多