public List<Models.Employer> GetEmployers()
{
List<Models.Employer> empList = new List<Models.Employer>();
var list = DataCentralDbContext.Employers.ToList();
foreach (Data.Web.Employer e in list)
{
empList.Add(Mapper.Map<Data.Web.Employer, Models.Employer>(e));
}
return empList;
}
我想測試上面的AutoMapper依賴的方法。 以下是測試方法的代碼。IMapable映射的AutoMapper測試
var data = new List<Data.Web.Employer>
{
new Data.Web.Employer {EmployerID= new Guid(), EmployerName = "BBB", AddressLine1="address 1", AddressLine2="address 2", City="City1",State="we",IsActive=true, PostalCode="12345" },
new Data.Web.Employer {EmployerID= new Guid(), EmployerName = "ZZZ",AddressLine1="address 1", AddressLine2="address 2", City="City1",State="we",IsActive=true, PostalCode="12345" },
new Data.Web.Employer {EmployerID= new Guid(), EmployerName = "AAA",AddressLine1="address 1", AddressLine2="address 2", City="City1",State="we",IsActive=true, PostalCode="12345" },
}.AsQueryable();
var mockSet = new Mock<DbSet<Data.Web.Employer>>();
mockSet.As<IQueryable<Data.Web.Employer>>().Setup(m => m.Provider).Returns(data.Provider);
mockSet.As<IQueryable<Data.Web.Employer>>().Setup(m => m.Expression).Returns(data.Expression);
mockSet.As<IQueryable<Data.Web.Employer>>().Setup(m => m.ElementType).Returns(data.ElementType);
mockSet.As<IQueryable<Data.Web.Employer>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());
var mockContext = new Mock<IDataCentralDbContext>();
mockContext.Setup(c => c.Employers).Returns(mockSet.Object);
var mapperMock = new Mock<IMapper>();
mapperMock.Setup(m => m.Map<CSF.Data.Web.Employer, CSF.Models.Employer>(It.IsAny<CSF.Data.Web.Employer>()));
var emplogic = new EmployerLogic(mockContext.Object, mapperMock.Object);
var result = emplogic.GetEmployers();
我找回正確的計數,但對象都是空。我嘗試使用返回,但它只返回一個對象。 是否可以退貨?
我建議你使用真正的Automapper類,因爲它在UT中的工作和在代碼中一樣。畢竟,你沒有測試它,你正在測試你的代碼,它檢查是否正確調用了'.Map <>'。 – zaitsman