简体   繁体   English

MVC Core 2.0单元测试和自动映射

[英]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. 我正在尝试单元测试一个使用Automapper ProjectTo的方法,我不知道如何在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: 消息:测试方法GotNext.Test.BusinessGenderServiceTest.GetTest抛出异常:

System.InvalidOperationException: Mapper not initialized. System.InvalidOperationException:Mapper未初始化。 Call Initialize with appropriate configuration. 使用适当的配置调用Initialize。 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. 如果您尝试通过容器或其他方式使用映射器实例,请确保您没有对静态Mapper.Map方法的任何调用,并且如果您使用的是ProjectTo或UseAsDataSource扩展方法,请确保传入适当的IConfigurationProvider实例。

I was able to solve this problem by configuring and initializing automapper in the Init method of each test class. 我能够通过在每个测试类的Init方法中配置和初始化automapper来解决这个问题。

For example 例如

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

You can configure AutoMapper in class like this: 您可以在类中配置AutoMapper,如下所示:

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 接下来在startup.cs的ConfigureService方法中使用它

services.AddSingleton(AutoMapperConfig.Initialize());

创建一个或多个类,用于配置AutoMapper并在Startup类中实例化(以及调用方法,如果适用)。

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). 我得到了同样的错误(“System.InvalidOperationException:Mapper未初始化。使用适当的配置调用Initialize ......”)当我无意中/盲目地切换AutoMapper的Instance API(我确实配置了)和AutoMapper的静态API(我没有配置)。

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(). 仔细查看错误消息中标记的代码行,我意识到我使用大写的'M'Mapper.Map()而不是我的实例成员小写'm'mapper.Map()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM