【问题标题】:Using IMapper in Integration Tests在集成测试中使用 IMapper
【发布时间】:2017-06-07 03:01:12
【问题描述】:

正如标题所说,我正在编写集成测试,并且确实希望将 IMapper 对象作为这些测试的一部分进行测试和初始化。

我使用 XUnit 作为测试框架并使用 Ninject 来处理依赖注入。

我习惯于使用静态 AutoMapper 方法,现在转而使用 IMapper 接口,这是我的一个存储库构造函数中的一个参数。

我有一个继承 NinjectModule 基类的 DependencyRegistrar 类。

我的加载方法如下:

public override void Load()
    {
        var automapperConfig = new MapperConfiguration(cfg => { cfg.AddProfile<AutoMapperProfile>(); });
        automapperConfig.AssertConfigurationIsValid();
        var mapper = automapperConfig.CreateMapper();

        Bind<IMapper>().ToConstant(mapper).InSingletonScope();
        Bind<IUserManager>().To<UserManager>().InTransientScope();
        Bind<IUserRepository>().To<UserRepository>().InTransientScope();
    }

此模块由 API 项目中的 NinjectWebCommon 类加载,但显然在集成测试期间没有加载。

ConfigurationSettingsEntity configurationSettings = new ConfigurationSettingsEntity(ConfigurationManager.AppSettings);
        var modules = new INinjectModule[] { new DependencyResolution.DependencyRegistrar(configurationSettings) };
        var kernel = new StandardKernel(modules);

所以,我的问题是,加载真正的映射器实现的最佳方式是什么,以便在构建集成测试时可以将该映射器传递到存储库的构造函数中?

UserRepository tester = new UserRepository(mapper);

【问题讨论】:

    标签: ninject integration automapper xunit


    【解决方案1】:

    放弃使用静态 Mapper 绝对值得付出努力 - 今后测试会容易得多!

    在我的单元测试中,我使用如下代码:

    var config = new MapperConfiguration(cfg => { 
        cfg.AddProfile<MyProfile>();
    });
    IMapper mapper = config.CreateMapper();
    

    在每个测试套件中,我手动指定这些测试所需的配置文件。

    【讨论】:

    • 这对于加载映射器非常有用。谢谢!
    猜你喜欢
    • 2021-01-05
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    • 2013-02-06
    • 2019-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多