我正在尝试为现有的MVC Web应用程序编写单元测试。因为我在自动映射器中遇到了一些问题(IMapper
)无论何时使用映射函数,它都会返回null
的值。如何模拟控制器中的自动映射器(IMapper)
我的控制器编码:
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);
}
}
映射器不工作其总是示出在控制器的null
值。请帮助我。提前致谢。
可能想问“为什么我需要?” Automapper可以断言映射配置是正确的。推测您的用户服务已经过测试。因此不需要测试你的控制器。 – Mardoxx
雅这很好。这是我的客户要求,他们也要求为控制器进行单元测试。然后在httppost中它可能有一些额外的功能,所以我需要这样做,请帮助我从此。 – Dinesh