MikeW
MikeW

Reputation: 4809

How to Mock part of an MVC Controller

I have a mock (using Moq) setup for a Mvc3 controller eg.

[TestMethod]
public void Step_One_Post_Should_Redirect_To_Step_Two()
{
    // this test checks that when I submit a type parameter of StepOneModel and
    // the next button was clicked Request["next"] ,  then goto Step Two
}

The only thing stopping this test running is the Save Method called from the controller, which fails as values aren't properly set in Session in this test context. Really I want to omit this database call from this unit test.

Basically how do I stup/mock the Save(model) call from the controller action?

[HttpPost]
public ActionResult Index(IStepViewModel step)
{
    // after model is deserialized
    if (!string.IsNullOrEmpty(Request["next"]))
    {
        Save(model)  <-- the bit blocking me
    }

    return View(model)  <-- the bit I want to assert against
}

Upvotes: 0

Views: 467

Answers (1)

gdoron
gdoron

Reputation: 150253

I suggest using the excellent library MvcContrib-test helpers

It gives you mocked session out of the box.

General Concepts

One of the major advantages of the new MVC.Net framework is the ease with which it can be tested. While this is generally true, there are a number of areas where testing the framework becomes difficult to do. The TestHelper assists by providing a Controller Factory that creates controllers with internal data members correctly initialized. These include:

  • HttpContext
  • HttpRequest
  • HttpResponse
  • HttpSession <-----------------------
  • Form
  • TempData
  • QueryString
  • ApplicationPath
  • PathInfo

Upvotes: 1

Related Questions