Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using IMapper in Integration Tests

As the title says, I'm writing integration tests and do want to test and initialize the IMapper object as part of these tests.

I am using XUnit as the testing framework and Ninject to handle dependency injection.

I'm used to using the static AutoMapper methods and am shifting to use the IMapper interface, which is a parameter in one of my repository constructors.

I have a DependencyRegistrar class that inherits the NinjectModule base class.

My Load method is below:

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();
    }

This module is loaded by the NinjectWebCommon class in the API project, but obviously doesn't get loaded during the integration tests.

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

So, my question is, what's the best way to load the real mapper implementation so that I can pass that mapper into my repository's constructor when I build out the integration test?

UserRepository tester = new UserRepository(mapper);
like image 843
Don Sartain Avatar asked Dec 01 '25 11:12

Don Sartain


1 Answers

It's definitely worth the effort to shift away from using the static Mapper - testing will be much easier going forward!

In my unit tests, I use code like the following:

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

In each test suite, I manually specify the profiles needed for those tests.

like image 80
Richard Avatar answered Dec 04 '25 05:12

Richard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!