Unit Testing MVC 4 RedirectToAction
14,071
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"]);
Related videos on Youtube
Author by
user962926
Updated on July 01, 2022Comments
-
user962926 almost 2 years
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 isnull
. 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!
-
Felix over 11 yearsAre you sure action actually returns RedirectToAction("Index", "Home")? There should be some logic in the Register action. If it returns any other kind of result and you are trying to make it as RedirectToRouteResult than you will get null.
-
Rickard over 11 yearsI got a RedirectToRouteResult object back when I tried. Are you sure your controller looks just like that?
-
VJAI over 11 yearsI guess you may be getting a ViewResult
-
-
GetFuzzy over 7 yearsThis should be marked as the correct answer. Also a duplicate of stackoverflow.com/questions/7601972/…
-
Richard Moore over 4 yearsWorked for me. but had to change the Assert.AreEqual("Index", action.RouteValues["action"]); to Assert.AreEqual("Index", result.RouteValues["action"]); - and left out result.RouteValues["action"].Equals("Index");