I am trying to unit test the redirection of my controller in MVC 4 .Net 4.5. Here is an example:
[TestMethod] public void Register_PassValidModel_RedirectToHomeIndexShouldBeTrue() { //Arrange var registerModel = new RegisterModel { Email = "[email protected]", Password = "password" }; //Assign var result = _controller.Register(registerModel) as RedirectToRouteResult; //Assert result.RouteValues["Action"].ShouldBeEqual("Index"); result.RouteValues["Controller"].ShouldBeEqual("Home"); }
Here is the controller:
[HttpPost] public ActionResult Register(RegisterModel model) { if (ModelState.IsValid) { var userToRegister = new User { Email = model.Email, Password = model.Password }; var service = new UserService(_userRepository); User user = service.RegisterUser(userToRegister); if (user.UserErrorMessages.Count != 0) { user.UserErrorMessages.ForEach(x => ModelState.AddModelError("", x)); return View(model); } SetCookie(model.Email); return RedirectToAction("Index", "Home"); } return View(model); }
The issue the variable result
in the Unit Test is null
. I found this code from someone who was working on a MVC 2 project and it seemed to work for him. Has something changed with MVC 4?
Thanks in advance!
Try this one hope it will useful for you
var result= (RedirectToRouteResult)controller.Register(registrModel); result.RouteValues["action"].Equals("Index"); result.RouteValues["controller"].Equals("Home"); Assert.AreEqual("Index", action.RouteValues["action"]); Assert.AreEqual("Home", action.RouteValues["controller"]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With