【发布时间】:2017-05-10 01:04:27
【问题描述】:
我正在尝试为我现有的 MVC Web 应用程序编写单元测试。因为我在 automapper (IMapper) 中遇到了一些问题,每当我使用 map 函数时,它都会返回 null 值。
我的控制器代码:
public class UserAdministrationController : BaseController
{
private readonly iUserService _userService;
private readonly IMapper _mapper;
public NewsController(iUserService userService, IMapper mapper)
{
_userService = userService;
_mapper = mapper;
}
public ActionResult Create(int CompanyID == 0)
{
UserDetail data = _userService(CompanyID);
var Modeldata = _mapper.Map<UserDetailViewModel, UserDetail>(data);
return View(Modeldata);
}
}
模拟映射代码:
public class MappingDataTest : CommonTestData
{
public Mock<IMapper> MappingData()
{
var mappingService = new Mock<IMapper>();
UserDetailViewModel interview = getUserDetailViewModel(); // get value of UserDetailViewModel
UserDetail im = getUserDetail(); // get value of UserDetails
mappingService.Setup(m => m.Map<UserDetail, UserDetailViewModel>(im)).Returns(interview);
mappingService.Setup(m => m.Map<UserDetailViewModel, UserDetail>(interview)).Returns(im);
return mappingService;
}
}
模拟代码:
[TestClass]
public class UserAdminControllerTest
{
private MappingDataTest _common;
[TestInitialize]
public void TestCommonData()
{
_common = new MappingDataTest();
}
[TestMethod]
public void UserCreate()
{
//Arrange
UserAdministrationController controller = new UserAdministrationController(_common.mockUserService().Object, _common.MappingData().Object);
controller.ControllerContext = _common.GetUserIdentity(controller);
// Act
ViewResult newResult = controller.Create() as ViewResult;
// Assert
Assert.IsNotNull(newResult);
}
}
Mapper 无法正常工作,它总是在控制器中显示null 值。请帮助我。提前致谢。
【问题讨论】:
-
可能想问,“我为什么需要这样做?” Automapper 可以断言映射配置是正确的。大概您的用户服务已经过测试。因此无需测试您的控制器。
-
是的,没关系。这是我的客户要求,他们也要求对控制器进行单元测试。然后在 httppost 它可能有一些附加功能,所以我需要这样做,请帮我解决这个问题。
标签: c# asp.net-mvc unit-testing mocking automapper