C# DotNet核心控制台应用程序:AutoMapper
您好,我正在DotNet核心控制台应用程序中使用AutoMapper 启动文件:C# DotNet核心控制台应用程序:AutoMapper,c#,unit-testing,.net-core,automapper,C#,Unit Testing,.net Core,Automapper,您好,我正在DotNet核心控制台应用程序中使用AutoMapper 启动文件: public class StartUp { public void ConfigureServices(IServiceCollection services) { services.AddAutoMapper(); } } 映射文件: public class MappingProfile: Profile { public MappingProfile() {
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 }));
}
}
单元测试类:
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);
}
}
参考链接:
运行测试文件时出现以下错误:
错误消息:
以下构造函数参数没有匹配的fixture
数据:IMapper映射器
谢谢我不太清楚您到底想做什么,但是如果您在测试项目中使用automapper,那么它可能会很有用:
[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>();
我不太清楚您到底想做什么,但是如果您在测试项目中使用automapper,那么它可能会很有用:
[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();
}
然后,您将有一个要测试的对象的实例。在单元测试中,我尽量避免调用我试图测试的类的抽象,因为我正在测试接口后面该类的实际工作,因为单元测试的启动方式与通常的不同,依赖项注入没有设置或使用。因此,当您的单元测试运行时,您会得到一个空引用异常,因为没有人传入Imapper 如果你想使用构造函数,我是你的单元测试,你会想做的
public test() {
_mapper = new Mapping profile();
}
然后,您将有一个要测试的对象的实例。在单元测试中,我尽量避免调用我试图测试的类的抽象,因为我正在测试接口后面该类的实际工作您通常不会在测试中使用DI,您只需自己创建映射器。您通常不会在测试中使用DI,您只需自己创建映射器即可。