我正在嘗試爲現有的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