這裏是我的控制器當使用automapper時如何對單元測試控制器?
[POST("signup")]
public virtual ActionResult Signup(UserRegisterViewModel user)
{
if (ModelState.IsValid)
{
var newUser = Mapper.Map<UserRegisterViewModel, User>(user);
var confirmation = _userService.AddUser(newUser);
if (confirmation.WasSuccessful)
return RedirectToAction(MVC.Home.Index());
else
ModelState.AddModelError("Email", confirmation.Message);
}
return View(user);
}
,這裏是我的單元測試:
[Test]
public void Signup_Action_When_The_User_Model_Is_Valid_Returns_RedirectToRouteResult()
{
// Arrange
const string expectedRouteName = "~/Views/Home/Index.cshtml";
var registeredUser = new UserRegisterViewModel { Email = "[email protected]", Password = "123456789".Hash()};
var confirmation = new ActionConfirmation<User>
{
WasSuccessful = true,
Message = "",
Value = new User()
};
_userService.Setup(r => r.AddUser(new User())).Returns(confirmation);
_accountController = new AccountController(_userService.Object);
// Act
var result = _accountController.Signup(registeredUser) as RedirectToRouteResult;
// Assert
Assert.IsNotNull(result, "Should have returned a RedirectToRouteResult");
Assert.AreEqual(expectedRouteName, result.RouteName, "Route name should be {0}", expectedRouteName);
}
,單元測試失敗就在這裏。
var result = _accountController.Signup(registeredUser) as RedirectToRouteResult;
當我調試我的單元測試時,我得到以下錯誤消息:「缺少類型映射配置或不支持的映射。」
我認爲它是因爲配置是在web項目中,而不是單元測試項目。我應該怎麼做才能解決它?
一些代碼在這裏解釋你的意思是非常好的。 – 2012-11-17 13:08:20
我一直在使用AutoMapper一年,並且我從未意識到IMappingEngine存在。我一直在嘲笑一切,但AutoMapper,並總是想知道爲什麼我的測試失敗,然後去看看,發現AutoMapper沒有配置。總是煩人。有界面會好得多:) – GetFuzzy 2014-05-24 21:13:05