vendredi 2 janvier 2015

Unit test of an action ends in an error

I have an Edit Post action method in my MVC4 application and I am trying to unit test this action. But, the Unit test fails with "NullReferenceException". Below is the unit test FYR.



[TestMethod]
public void EditAction_Should_Redirect_When_Update_Successful()
{
// Arrange

var mockHttpContext = new Mock<HttpContextBase>();
var mockRequest = new Mock<HttpRequestBase>();
mockHttpContext.Setup(x => x.Request).Returns(mockRequest.Object);


// tell the mock to return "POST" when HttpMethod is called
mockRequest.Setup(x => x.HttpMethod).Returns("POST");

mockRequest.SetupGet(req => req.Form).Returns(new FormCollection());

var controller = GetTheController();
var id = 1;

// assign the fake context
var context = new ControllerContext(mockHttpContext.Object,
new RouteData(),
controller);
controller.ControllerContext = context;


var formValues = new FormCollection() {
{"MyModel.Id", "1" },
{"MyModel.ActivityDescription", "This is another description"},
{"MyModel.CreatedDate", "31-12-2014"},
{"MyModel.UserId", "1"},
{"MyModel.IsCompleted", "false"}
};

// Act
var result = controller.Edit(id, formValues) as RedirectToRouteResult;

// Assert
Assert.AreEqual("List", result.RouteValues["Action"]);
Assert.AreEqual(id, result.RouteValues["id"]);
}


Edit action method is below -



[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id, FormCollection collection)
{
var item = _itemsRepository.Find(id);
var viewResult = ValidateItem(item);
if (viewResult != null)
return viewResult;

//Unit test is failing at this step.
TryUpdateModel(item);
if (ModelState.IsValid)
{
_itemsRepository.Edit(item);
return RedirectToAction("Index");
}
else return View(item);
}


Below is the stacktrace for reference -


Test Outcome: Failed Test Duration: 0:00:00.3306816


Result Message:



Test method MvcToDoListItemsDemo.Tests.TodoControllerTest.EditAction_Should_Redirect_When_Update_Successful threw exception:
System.NullReferenceException: Object reference not set to an instance of an object.
Result StackTrace:
at Microsoft.Web.Infrastructure.DynamicValidationHelper.DynamicValidationShim.IsValidationEnabled(HttpContext context)
at Microsoft.Web.Infrastructure.DynamicValidationHelper.ValidationUtility.IsValidationEnabled(HttpContext context)
at Microsoft.Web.Infrastructure.DynamicValidationHelper.ValidationUtility.GetUnvalidatedCollections(HttpContext context, Func`1& formGetter, Func`1& queryStringGetter)
at System.Web.Helpers.Validation.Unvalidated(HttpRequest request)
at System.Web.Mvc.FormValueProviderFactory.<.ctor>b__0(ControllerContext cc)
at System.Web.Mvc.FormValueProviderFactory.GetValueProvider(ControllerContext controllerContext)
at System.Web.Mvc.ValueProviderFactoryCollection.<>c__DisplayClassc.<GetValueProvider>b__7(ValueProviderFactory factory)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at System.Web.Mvc.ValueProviderFactoryCollection.GetValueProvider(ControllerContext controllerContext)
at System.Web.Mvc.ControllerBase.get_ValueProvider()
at System.Web.Mvc.Controller.TryUpdateModel[TModel](TModel model)


Could someone please advise if I am doing anything wrong here ?


Regards, Ram


Aucun commentaire:

Enregistrer un commentaire