[TestMethod] public void Can_Login_With_Valid_Credentials() { //Arrange Mock<IMembershipRepository> mockRepository = new Mock<IMembershipRepository>(); Mock<LoginViewModel> mockModel = new Mock<LoginViewModel>(); mockModel.Setup(x => x.IsLoggedIn()).Returns(true); AccountController target = new AccountController(mockRepository.Object); //Act ActionResult result = target.Login(mockModel.Object); //Assert Assert.IsNotInstanceOfType(result, typeof(ViewResult)); } And ActionResult in the controller
public ActionResult Login(LoginViewModel viewModel) { string returnUrl = (string)TempData["ReturnUrl"]; if (ModelState.IsValid) { LoginViewModel model = new LoginViewModel(repository, viewModel); if (model.IsLoggedIn()) { if (String.IsNullOrEmpty(returnUrl)) return RedirectToAction("Index", "Home"); else return Redirect(returnUrl); } else { ModelState.AddModelError("Email", ""); ModelState.AddModelError("Password", ""); } } return View(viewModel); } I'm having problems with mocking model.IsLoggedIn() in the ActionMethod, and it is probably because I'm creating a new instance of the viewmodel LoginViewModel in that ActionMethod. That is why mockModel.Setup(x => x.IsLoggedIn()).Returns(true); in the unit test is not caching it because there is a new instance of the class that has that method.
Is there any way i can mock model.IsLoggedIn() in the ActionMethod and make it return true?
LoginViewModelobject instead of manipulating the existing one?LoginViewModelthat you pass in is not the instance thatIsLoggedInis actually called upon, hence the setup not matching.protected virtual CreateLoginViewModelin your controller would allow you to manipulate it through normal mocking tools. Or reuse the model as Jeroen suggests.