您好我在DotNet Core Console应用程序中使用AutoMapper
启动文件:
public class StartUp
{
public void ConfigureServices(IServiceCollection services) {
services.AddAutoMapper();
}
}
映射文件:
public class MappingProfile: Profile {
public MappingProfile() {
CreateMap < Employee, EmployeeModel > ().ForMember(dest => dest.Address, opts => opts.MapFrom(src => new Address {
City = src.City, State = src.State }));
}
}
UnitTest类:
public class UnitTest1
{
private readonly IMapper _mapper;
public UnitTest1(IMapper mapper)
{
_mapper = mapper;
}
[Fact]
public void Test1()
{
Employee emp = new Employee ();
emp.Id=1;
emp.Name="Test";
var empmodel = _mapper.Map < Employee, EmployeeModel > (emp);
Assert.Equal(empmodel.Name,"Test");
Assert.Equal(empmodel.Id,1);
}
}
参考链接:https://www.c-sharpcorner.com/article/how-to-implement-automapper-in-asp-net-core-mvc-application/
我在运行测试文件时遇到以下错误:错误消息:
以下构造函数参数没有匹配的fixture数据:IMapper mapper
谢谢
我不太清楚你要做什么,但是如果你在测试项目中使用了者,那么它可能会很有用:
[Fact]
public void Test1()
{
var employee = new Employee
{
AddressEmployee = new Address
{
City = "SomeCity"
}
};
//initialize automapper and register mapping profile
var mockMapper = new MapperConfiguration(cfg => cfg.AddProfile(new EmployeeProfile()));
//create new mapper
var mapper = mockMapper.CreateMapper();
//map
var employeeModel = mapper.Map<EmployeeModel>(employee);
// do assert or another stuff
}
顺便说一句,如果类中字段的名称相同,则无需指定从哪里到哪个地图。指定类就足够了。
CreateMap<Employee, EmployeeModel>();
因为您的单元测试没有像往常那样启动,所以不会设置或使用依赖注入。因此,当您的单元测试运行时,您会得到一个空引用异常,因为没有人在Imapper中传递。
如果你想使用构造函数我是你想要做的单元测试
public test() {
_mapper = new Mapping profile();
}
然后你将有一个你想要测试的对象的实例。在单元测试中,我试图避免调用我试图测试的类的抽象,因为我正在测试接口后面的类的实际工作情况