I am adding unit testing to the NerdDinner solution, and ran across this. I am testing the Edit POST method, given here:
[AcceptVerbs(HttpVerbs.Post), Authorize]
public virtual ActionResult Edit(int id, FormCollection formValues)
{
Dinner dinner = dinnerRepository.GetDinner( id );
if (!dinner.IsHostedBy(User.Identity.Name))
{
return View(Views.InvalidOwner);
}
try
{
UpdateModel(dinner);
dinnerRepository.Save();
//return RedirectToAction("Details", new { id = dinner.DinnerID });
return RedirectToAction(Actions.Details(dinner.DinnerID));
}
catch (Exception ex)
{
foreach (var issue in dinner.GetRuleViolations())
{
ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
}
return View(new DinnerFormViewModel(dinner));
}
}
The System.TypeInitializationException is thrown on the “return RedirectToAction…” line, and says “The type initializer for ‘MVC’ threw an exception.”
When I replace the T4MVC-encoded line with the original line (commented out above), I do not get the exception.
Here is the unit test code:
[TestMethod]
public void EditAction_Should_Redirect_When_Update_Successful()
{
// Arrange
var controller = CreateDinnersControllerAs("Some User");
var formValues = new FormCollection
{
{ "Title", "Another Value" },
{ "Description", "Another Description" }
};
controller.ValueProvider = formValues.ToValueProvider();
// Act
var result = controller.Edit(1, formValues) as RedirectToRouteResult;
// Assert
Assert.IsNotNull(result);
Assert.AreEqual("Details", result.RouteValues["Action"]);
}
I have a couple of ideas what may be causing this exception to be thrown, but I’m not sure enough to posit here. I’m totally unclear as to how to fix it.
Ideas?
Dave
MVC is a class generated by T4MVC. The error you are seeing simply means that an exception was thrown inside the constructor of this generated MVC class (note that “constructor” in this sense also means initialization of any fields that are assigned a value where declared).
Open and save the T4MVC.tt file to ensure your code generated file is up to date. If that doesn’t help and you’re using the most recent version available, set a breakpoint in the constructor of the generated MVC class to find out what breaks it.