我正在测试这个方法,它最终会映射到我的 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/