4

I want to write a unit test to ensure that the view I am returning is the correct one.

My plan is to write a test that first invokes the controller and then calls the ActionResult method I plan to test I thought I could write something like

Controller controller = new HomeController();
var actionresult = controller.Index();
Assert.False(actionresult.ToString(), String.Empty);

which would then allow me to parse the actionresult for the test value. However I cannot directly instantiate the public ActionResult Index() method.

How do I do this?

4
  • "However I cannot directly instantiate the public ActionResult Index() method " ? Can you explain why?
    – J.W.
    Commented Jun 9, 2009 at 12:55
  • What do you mean by you cannot directly instantiate the method? Commented Jun 9, 2009 at 12:56
  • I meant I typed "controller." and Index would not appear as one of the methods I could instantiate.
    – Nissan
    Commented Jun 9, 2009 at 13:01
  • Does your code compile at all?
    – J.W.
    Commented Jun 9, 2009 at 13:05

2 Answers 2

4

The test helpers in MVCContrib will help you here.

ViewResult result = controller.Index().AssertViewRendered().ForView("Blah");
1

Here's an example from Professional ASP.NET MVC 1.0 (book):


[TestMethod]
public void AboutReturnsAboutView()
{
     HomeController controller = new HomeController();
     ViewResult result = controller.About() as ViewResult;

     Assert.AreEqual("About", result.ViewName);
}

Note that this will fail if you don't return an explicit view in your controller method, i.e. do this:


     Return(View("About"));

not this:


     Return(View());

Or the test won't pass. You should only need to do this if your method will ever return more than one view, otherwise you should return an implicit view anyway and not bother testing the framework.

2
  • 1
    Testing out your code, it should be ViewResult result = controller.About() as ViewResult; no 's', but it is looking good so far. Will award this answer as correct if it works when I finish
    – Nissan
    Commented Jun 9, 2009 at 13:12
  • Yeah sorry, that was a typo. It's hard to copy and paste from an actual book :) Commented Jun 9, 2009 at 18:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.