gpt4 book ai didi

unit-testing - MVC Core 2.0 单元测试和自动映射器

转载 作者:行者123 更新时间:2023-12-01 08:49:24 25 4
gpt4 key购买 nike

我正在尝试对使用 Automapper ProjectTo 的方法进行单元测试,但我不确定如何在 MVC Core 中注册映射。我正在使用内置的单元测试。

以下是我的单元测试。

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

}
}

我在运行测试时收到以下错误:

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.

最佳答案

我能够通过在每个测试类的 Init 方法中配置和初始化 automapper 来解决这个问题。

例如

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

关于unit-testing - MVC Core 2.0 单元测试和自动映射器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46457946/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com