2

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?

tereško
58.5k26 gold badges100 silver badges151 bronze badges
asked Dec 10, 2008 at 21:03

1 Answer 1

5

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.

answered Dec 10, 2008 at 21:13

1 Comment

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.