views:

1261

answers:

1

I've been going through the various tutorials regarding the right way to unit test controller logic. Take the following action:

    public ActionResult Login()
    {
        //Return the index view if we're still here
        return View();
    }

Word on the street is to wire up a test method similar to this:

    [TestMethod]
    public void TestLoginView()
    {
        //Set up an instance of the controller
        var thisController = new UserController();

        //Invoke the index action
        var actionResult = (ViewResult)thisController.Login();

        //Validate the test
        Assert.AreEqual("Login", actionResult.ViewName);
    }

The assert works as expected. However, this controller has a base class that overrides the OnActionExecuting function in order to set up the various page element chrome (navigation elements, breadcrumbs, etc.) This bit of logic never gets hit.

I can easily test the models being used in the controller, however I would like to have my testing at the controller layer. Ideas?

+3  A: 

The test framework only invokes the particular method under test, it doesn't mimic the ASP.NET MVC framework and fire all of the events that would normally happen. I would test your OnActionExecuting logic in separate tests to make sure it works. This test should only test the functionality in the associated controller method. If you have particular expectations based on other events firing, you'll need to mock these up in the controller context prior to calling the controller method.

tvanfosson
I'm a little concerned that it's possible to short-circuit the event stack this way.
bxlewi1