当我在代码中实施IReadOnlyList
时,我的单元测试投了AutoMapperMappingException
。
从挖掘文章和文档,我的猜测是AutoMapper需要对readonly
类型进行特殊编码。这会是什么样的?
注意:我尝试了Mapper.AssertConfigurationIsValid();
作为另一篇建议,但没有改进。
测试名称:CreateOrder_ValidContract_CreatesNewOrder测试 FullName:ACME.Maintenance.Domain.Test.OrderServiceTest.CreateOrder_ValidContract_CreatesNewOrder 测试源:C:\ Users \ me \ documents \ visual studio 2015年\项目\ ACME.Maintenance \ ACME.Maintenance.Domain.Test \ OrderServiceTest.cs :第65行测试结果:测试持续时间失败:0:00:00.0233941
结果StackTrace:在lambda_method(Closure,ContractDto,Contract ,ResolutionContext)at ACME.Maintenance.Domain.ContractService.GetById(String contractId)in C:\ Users \ me \ documents \ visual studio 2015年\项目\ ACME.Maintenance \ ACME.Maintenance.Domain \ ContractService.cs:行 34点 ACME.Maintenance.Domain.Test.OrderServiceTest.CreateOrder_ValidContract_CreatesNewOrder() 在C:\ Users \ me \ documents \ visual studio中 2015年\项目\ ACME.Maintenance \ ACME.Maintenance.Domain.Test \ OrderServiceTest.cs:行 69结果消息:测试方法 ACME.Maintenance.Domain.Test.OrderServiceTest.CreateOrder_ValidContract_CreatesNewOrder 引发异常:AutoMapper.AutoMapperMappingException:缺少类型 地图配置或不支持的映射。
映射类型:ContractDto - >合同
ACME.Maintenance.Domain.DTO.ContractDto - > ACME.Maintenance.Domain.Contract
Mapper.Initialize(cfg => cfg.CreateMap<ContractDto, Contract>());
Mapper.Initialize(cfg => cfg.CreateMap<PartDto, Part>());
[TestMethod]
public void CreateOrder_ValidContract_CreatesNewOrder()
{
//Arrange
var orderService = new OrderService();
var contractService = new ContractService(_contractRepository);
var contract = contractService.GetById(ValidContractId);
// Act
var newOrder = orderService.CreateOrder(contract);
// Assert
Assert.IsInstanceOfType(newOrder, typeof(Order));
Guid guidOut;
Assert.IsTrue(Guid.TryParse(newOrder.OrderId, out guidOut));
Assert.AreEqual(newOrder.Status, ContractStatus.New);
Assert.IsInstanceOfType(newOrder.Items, typeof(IReadOnlyList<OrderItem>));
}
ContractService类:
public Contract GetById(string contractId)
{
var contractDto = _contractRepository.GetById(contractId);
var contract = Mapper.Map<ContractDto, Contract>(contractDto);
Mapper.AssertConfigurationIsValid();
return contract;
}
合同类:
public class Contract
{
public string ContractId { get; set; }
public DateTime ExpirationDate { get; set; }
}
ContractDto类:
public class ContractDto
{
public string ContractId { get; set; }
public DateTime ExpirationDate { get; set; }
}
答案 0 :(得分:8)
您的问题是您多次拨打Mapping.Initialize
:它不是附加的,因此您要覆盖之前的映射,这就是为什么您将地图从ContractDto
丢失到Contract
因此,在测试的Setup
方法中,您应该这样称呼它:
Mapper.Initialize(cfg => {
cfg.CreateMap<ContractDto, Contract>();
cfg.CreateMap<PartDto, Part>();
});