Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit-test an action, when return type is ActionResult?

I have written unit test for following action.

[HttpPost] public ActionResult/*ViewResult*/ Create(MyViewModel vm) {     if (ModelState.IsValid)     {         //Do something...         return RedirectToAction("Index");     }      return View(vm); } 

Test method can access Model properties, only when return type is ViewResult. In above code, I have used RedirectToAction so return type of this action can not be ViewResult.

In such scenario how do you unit-test an action?

like image 574
Abhijeet Avatar asked Sep 18 '13 06:09

Abhijeet


2 Answers

So here is my little example:

public ActionResult Index(int id) {   if (1 != id)   {     return RedirectToAction("asd");   }   return View(); } 

And the tests:

[TestMethod] public void TestMethod1() {   HomeController homeController = new HomeController();   ActionResult result = homeController.Index(10);   Assert.IsInstanceOfType(result,typeof(RedirectToRouteResult));   RedirectToRouteResult routeResult = result as RedirectToRouteResult;   Assert.AreEqual(routeResult.RouteValues["action"], "asd"); }  [TestMethod] public void TestMethod2() {   HomeController homeController = new HomeController();   ActionResult result = homeController.Index(1);   Assert.IsInstanceOfType(result, typeof(ViewResult)); } 

Edit:
Once you verified that the result type is ViewResut you can cast to it:

ViewResult vResult = result as ViewResult; if(vResult != null) {   Assert.IsInstanceOfType(vResult.Model, typeof(YourModelType));   YourModelType model = vResult.Model as YourModelType;   if(model != null)   {     //...   } } 
like image 119
Péter Avatar answered Sep 27 '22 23:09

Péter


Please note that

Assert.IsInstanceOfType(result,typeof(RedirectToRouteResult));  

has been deprecated.

The new syntax is

Assert.That(result, Is.InstanceOf<RedirectToRouteResult>()); 
like image 24
Esteban Chi Avatar answered Sep 28 '22 00:09

Esteban Chi