问题
I'm trying to test the path from my ASP.NET Core Controller to the DB, through repository which includes the usage of AutoMapper.
Here's my repository:
using System;
using System.Linq;
using AutoMapper;
using DS.DTO.MasterData;
using DS.Utilities.DSExceptions;
using Microsoft.Extensions.Logging;
using Omu.ValueInjecter;
namespace DS.MasterData.Repositories
{
public class PersonFactRepository : IPersonFactRepository
{
private readonly Database.MasterDataContext dbContext;
private readonly ILogger<PersonFactRepository> logger;
private readonly IMapper mapper;
public PersonFactRepository(ILogger<PersonFactRepository> logger, Database.MasterDataContext dbcontext, IMapper mapper)
{
this.dbContext = dbcontext;
this.mapper = mapper;
this.logger = logger;
}
public PatientDto CreatePatient(CreatePatientDto inModel)
{
var dbPersonDim = mapper.Map<CreatePatientDto, Database.PersonDim>(inModel);
var dbAddressDim = mapper.Map<CreatePatientDto, Database.AddressDim>(inModel);
var dbPhoneDim = mapper.Map<CreatePatientDto, Database.PhoneDim>(inModel);
var dbPersonFact = new Database.PersonFact { FactId = Guid.NewGuid() };
dbPersonDim.PersonFact = dbPersonFact;
dbAddressDim.PersonFact = dbPersonFact;
dbPhoneDim.PersonFact = dbPersonFact;
dbPersonDim.InitDates();
dbAddressDim.InitDates();
dbPhoneDim.InitDates();
dbContext.SaveChanges();
var returnVal = new PatientDto();
returnVal.InjectFrom(dbPersonDim)
.InjectFrom(dbAddressDim)
.InjectFrom(dbPhoneDim);
return returnVal;
}
}
}
My AutoMapper configuration:
public class AutoMapperConfig : Profile
{
public AutoMapperConfig()
{
CreateMap<CreatePatientDto, Database.PersonDim>(MemberList.None).ReverseMap();
CreateMap<CreatePatientDto, Database.AddressDim>(MemberList.None).ReverseMap();
CreateMap<CreatePatientDto, Database.PhoneDim>(MemberList.None).ReverseMap();
}
}
My problem is how do I get my Mapper configuration into my fakeMapper?
var inMemDB = Fakes.FakeDB.DB;
var loggerCntl = Substitute.For<ILogger<Controllers.PatientController>>();
var loggerPersonFactRepo = Substitute.For<ILogger<Repositories.PersonFactRepository>>();
AutoMapper.IMapper fakeMapper = ????
var personRepo = new PersonFactRepository(loggerPersonFactRepo, inMemDB, fakeMapper);
It's on purpose that I'm going for a integration test, as I want my test to be able to post data to the controller and test if the right data ends up in the right tables.
回答1:
Create a mapper provider
public class MapperProvider { public MapperProvider() { } public MapperConfiguration GetMapperConfig() { var mce = new MapperConfigurationExpression(); mce.AddProfile<AutoMapperConfig>(); var mc = new MapperConfiguration(mce); return mc; } }
Register the mapping config
AutoMapper.IMapper fakeMapper = new Mapper(new MapperProvider().GetMapperConfig());
来源:https://stackoverflow.com/questions/50944862/a-kind-of-integration-testing-in-asp-net-core-with-ef-and-automapper