A week or so ago, I wrote an entry about controller testing with the ControllerBuilder. In it I mentioned the "solution" obviously wasn't the best, and hoped that the work-around we were using wouldn't be needed for much longer. Well, last Wednesday the MVC team published a preview of preview 3. There were a number of changes included in this build, but I'm going to talk about controller testing improvements.
What We Did Way Back Last Week
Last week, we used a test helper from the MvcContrib project. Basically, the controller builder constructed an instance of our controller using Dynamic Proxy and then implemented an interceptor so it could grab data that we could use in our tests. It is quite a bit of work for something so straightforward. All we wanted to do was execute our action and see if it rendered the correct view.
What's My ActionResult?
If you remember, our controller actions are nothing more than public methods on a controller class. When you call the action from your browser, the ASP.NET MVC simply wires up a request that eventually executes the specified method. Nothing too crazy. The methods didn't even return anything; they were simply declared void.
Since we're working with preview releases here, you can't really expect things not to change. With the latest build, controller methods/actions now return an instance of ActionResult. What is ActionResult? ActionResult is an abstract class that is used to return the result of the action. A result can be a rendered view, a redirect to an action, or even a regular HTTP redirect to another location entirely.
Getting the Result
Now, here's where you may notice the difference. In our previous controller code, if we wanted to redirect to an action, we could just call RedirectToAction in the middle of the action code and be done with it. RedirectToAction, and the other helper methods, all return instances of some form of ActionResult. RedirectToAction now returns ActionRedirectResult. RenderView returns RenderViewResult. What does this mean? When you call the helper methods, you need return their result now. Here's an example:
public ActionResult Index()
{
return RenderView("index");
}
As you can see, you just need to ensure you return the result. This result is then used by the framework and you can also use it for testing. The code below illustrates a very simple test using the new build.
[Test]
public void BookController_Ensure_Index_Action_Renders_Index_View()
{
BookController controller = new BookController();
var result = controller.Index() as RenderViewResult;
Assert.IsNotNull(result);
Assert.AreEqual("index", result.ViewName);
}
I'll have more on this subject, and a real world example that puts them all together in a little while.
Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5