1

I have problem with testing classes, which using UpdateModel() method. I get System.NullReferenceException. I use NUnit. This is my method from HomeController:

    public ActionResult ProjectsEdit(Projects model)
    {
        var projects = db.Projects.First();
        projects.Content = model.Content;
        UpdateModel(projects);
        db.SaveChanges();
        return RedirectToAction("Projects");            
    }

Here is test class:

    [Test]
    public void ProjectsEditPostTest()
    {
        var routeData = new RouteData();
        var httpContext = MockRepository.GenerateStub<HttpContextBase>();
        //var httpContext = new FakeHttpContext("Edit");
        FormCollection formParameters = new FormCollection();
        ControllerContext controllerContext =
        MockRepository.GenerateStub<ControllerContext>(httpContext,
                                                            routeData,
                                                            controller);
        controller.ControllerContext = controllerContext;

        // Act
        string newContent = "new content";
        Projects projects = new Projects { ID = 1, Content = newContent };
        controller.ProjectsEdit(projects);

        // Assert
        Assert.AreEqual(newContent, controller.db.Projects.First().Content);            
    }

What should I do to make it works?

tereško
  • 58,060
  • 25
  • 98
  • 150
Jacob Jedryszek
  • 6,365
  • 10
  • 34
  • 39

1 Answers1

4

Just add the following line in the Assert phase:

controller.ValueProvider = formParameters.ToValueProvider();

It assigns a value provider to the controller on which the UpdateModel method relies. This value provider is associated to the FormCollection variable you have defined and which allows you to pass some values.

You may also check a similar answer which uses MvcContrib.TestHelper to simplify the Arrange phase.

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928