c# - xUnit测试asp net core Mapper未初始化

标签 c# unit-testing testing xunit

我正在测试这个方法,它最终会映射到我的 DTO

public async Task<IActionResult> Get()
        {
            var currencies = await _repository.GetCurrencies().ToListAsync().ConfigureAwait(false);
            if (currencies.Count == 0)
                return NoContent();

            return Ok(currencies.ToDto());
        }

作为此方法的返回,我收到以下错误:

Message: 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.

我用静态方法做自动映射

public static List<CurrencyDTO> ToDto(this List<Currency> model)
        {
            return Mapper.Map<List<Currency>, List<CurrencyDTO>>(model);
        }

当我只运行这个测试时它通过了但是当我挤压每个人时它会说话

我已经尝试过让构建器初始化映射器,但继续出错,测试仅在单独运行时通过

public class CurrenciesControllerTest
    {
        public CurrenciesControllerTest()
        {
            AutoMapperConfig.RegisterMappings();
        }
        private Mock<IReimbursementRepository> _repository = new Mock<IReimbursementRepository>();
        [Fact]
          public async Task Should_return_all_currencies()
        {
            var mock = Currencyfactory().AsQueryable().BuildMock();
            _repository.Setup(x => x.GetCurrencies()).Returns(mock.Object);

            var controller = new CurrenciesController(_repository.Object);
            var response = await controller.Get().ConfigureAwait(false) as OkObjectResult;`enter code here`

            Assert.Equal(response.StatusCode, (int)HttpStatusCode.OK);
        }
    }

最佳答案

我的解决方案,配置AutoMapperConfig

 public class AutoMapperConfig
    {
        public static object thisLock = new object();
        public static void Initialize()
        {
            lock (thisLock)
            {
                AutoMapper.Mapper.Reset();
                AutoMapper.Mapper.Initialize(cfg => { });
            }
        }
    }
}

关于c# - xUnit测试asp net core Mapper未初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56453070/

相关文章:

ios - 用户界面测试 : Two elements w/same accessibilityTitle

c# - float 是否可以通过 double 往返而不损失精度?

javascript - 使用 React、Enzyme、Jest 测试嵌套 div 中是否存在特定链接

c# - FileStream 和 System.IO.File 方法之间的文件访问差异

unit-testing - 当我还没有发布它时,我如何为我的 JSON 模式提供它的 $id 的绝对 URL 因为它还没有经过测试?

c# - Moq.Mock Exception with invocation failed with mock behavior strict

unit-testing - 测试持续集成的分支是什么?

testing - 如何重用 puppeteer 测试

c# - 为什么 "The LINQ expression ' x' 无法翻译”?我没有使用 "Where()"

c# - 当用户将鼠标悬停在 TreeView 控件的特定 TreeNode 控件上时显示不同的光标