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?
Just add the following line in the Assert phase:
It assigns a value provider to the controller on which the
UpdateModelmethod 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.