Napoleon Ike Jones
Napoleon Ike Jones

Reputation: 565

MVC Core 2.0 Unit Testing and Automapper

I am attempting to Unit Test a method that uses Automapper ProjectTo and I'm not sure how to register the mappings in MVC Core. I am using the built in unit testing.

The following is my unit test.

 [TestClass]
public class BusinessGenderServiceTest
{
    [ClassInitialize]
    public static void Init(TestContext context)
    {

    }
    [TestMethod]
    public void GetTest()
    {
        var options = new DbContextOptionsBuilder<GotNextDbContext>()
            .UseInMemoryDatabase(databaseName: "GetTest")
            .Options;

        using (var context = new GotNextDbContext(options))
        {


            context.GenderLanguage.Add(new GenderLanguage { Id = 1, Name = "Male", Language = 1 });
            context.GenderLanguage.Add(new GenderLanguage { Id = 2, Name = "Female", Language = 1 });
            context.GenderLanguage.Add(new GenderLanguage { Id = 3, Name = "Hombre", Language = 2 });
            context.GenderLanguage.Add(new GenderLanguage { Id = 4, Name = "Hombre", Language = 2 });
            context.SaveChanges();
        }
            using (var context = new GotNextDbContext(options))
            {
                var service = new GenderService(context);
                var result = service.Get(1);
                Assert.AreEqual(2, result.Count());
            }

    }
}

I am getting the following error when I run the test:

Message: Test method GotNext.Test.BusinessGenderServiceTest.GetTest threw exception:

System.InvalidOperationException: Mapper not initialized. Call Initialize with appropriate configuration. If you are trying to use mapper instances through a container or otherwise, make sure you do not have any calls to the static Mapper.Map methods, and if you're using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance.

Upvotes: 3

Views: 3482

Answers (4)

Napoleon Ike Jones
Napoleon Ike Jones

Reputation: 565

I was able to solve this problem by configuring and initializing automapper in the Init method of each test class.

For example

[ClassInitialize]
    public static void Init(TestContext testContext)
    {
        var mappings = new MapperConfigurationExpression();
        mappings.AddProfile<LocationProfile>();
        mappings.AddProfile<CompanyProfile>();
        Mapper.Initialize(mappings);
    }

Upvotes: 8

Bob Tabor
Bob Tabor

Reputation: 987

I got this same error ("System.InvalidOperationException: Mapper not initialized. Call Initialize with appropriate configuration. ...") when I inadvertently / mindlessly switched between AutoMapper's Instance API (which I did have configured) and AutoMapper's Static API (which I did NOT have configured).

Looking closely at the line of code flagged in the error message, I realized I used upper-case 'M' Mapper.Map() instead of my instance member lower-case 'm' mapper.Map().

Upvotes: 0

Kerni
Kerni

Reputation: 121

You can configure AutoMapper in class like this:

public static class AutoMapperConfig
    {
        public static IMapper Initialize()
        {
            return new MapperConfiguration((cfg => 
            {
                cfg.CreateMap<User, UserDto>();

            })).CreateMapper();
        }
    }

And next use it in startup.cs ConfigureService method

services.AddSingleton(AutoMapperConfig.Initialize());

Upvotes: 1

Moho
Moho

Reputation: 16498

Create a class or classes that configure AutoMapper and instantiate (and call methods, if applicable) in the Startup class.

Upvotes: 0

Related Questions