UpdateModel cannot return a correct result by using mock form collection value
-
29-10-2019 - |
Question
I have two test method calling to controller:
This one passed:
[Test]
public void EditAction_Should_Redirect_When_Update_Successful()
{
// Arrange
var controller = CreatePaperControllerAs("SomeUser");
const int id = 2;
FormCollection formValues = new FormCollection() {
{ "IM_Paper.Title", "Another value" },
{ "IM_Paper.Abstract", "Another description" }
};
controller.ValueProvider = formValues.ToValueProvider();
// Act
var result = controller.Edit(id, formValues) as RedirectToRouteResult;
// Assert
Assert.AreEqual("Details", result.RouteValues["Action"]);
Assert.AreEqual(id, result.RouteValues["id"]);
}
This one fails:
[Test]
public void EditAction_Should_Redisplay_With_Errors_When_Update_Fails()
{
// Arrange
var controller = CreatePaperControllerAs("SomeUser");
int id = 1;
FormCollection formValues = new FormCollection() {
{ "IM_Paper.Year","xxx"}
};
controller.ValueProvider = formValues.ToValueProvider();
// Act
var result = controller.Edit(id, formValues) as ViewResult;
// Assert
Assert.IsNotNull(result, "Expected redisplay of view");
Assert.IsTrue(result.ViewData.ModelState.IsValid, "Expected Errors");
}
The Action Result in the controller is
[HttpPost, Authorize]
public ActionResult Edit(int id, FormCollection collection)
{
IM_Paper paper = _paperRepository.GetPaperById(id);
if (!paper.IsPostedByUser(User.Identity.Name))
return View("InvalidOwner");
try
{
UpdateModel(paper, "IM_Paper" );
_paperRepository.Save();
return RedirectToAction("Details", new { id = paper.PaperId });
}
catch
{
return View(paper);
}
}
However, the try-catch block never catch an exception (The "IM_Paper.Year" should be an int). So the controller always return Action result as RedirectToAction. Even for the first one, the in memory data did not change.
Do you have any idea why this happen? For the class "IM_Paper", I used the POCO generator and generated from an entity framework. The class looks like this:
public partial class IM_Paper
{
#region Primitive Properties
public virtual int PaperId
{get;set;}
public virtual string Author
{get;set;}
public virtual Nullable<int> Year
{get;set;
} ...
Solution
Found the answer, I haven't bounded the attributes to the IM_Paper class.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow