I have an example ASP.NET MVC 3 web application that follows the Jonathan McCracken Test-Drive Asp.NET MVC (by the way, a great book), and I came across a problem. Note that I use MVCContrib, Rhino, and NUnit.
[Test] public void ShouldSetLoggedInUserToViewBag() { var todoController = new TodoController(); var builder = new TestControllerBuilder(); builder.InitializeController(todoController); builder.HttpContext.User = new GenericPrincipal(new GenericIdentity("John Doe"), null); Assert.That(todoController.Index().AssertViewRendered().ViewData["UserName"], Is.EqualTo("John Doe")); }
The above code always causes this error:
System.AccessViolationException: attempt to read or write protected memory. This often indicates that another memory is corrupted.
The controller action code is as follows:
[HttpGet] public ActionResult Index() { ViewData.Model = Todo.ThingsToBeDone; ViewBag.UserName = HttpContext.User.Identity.Name; return View(); }
From what I found out, the application seems to crash due to two assignments in the controller action. However, I do not see how this happens !?
Can someone help me determine a solution to this problem.
Thanks.
Change 1
I conducted several experiments to understand what the problem is. When you delete the ViewData,Model destination ViewData,Model problem goes beyond the Expected result to be of type ViewResult. It is actually of type ViewResult. Expected result to be of type ViewResult. It is actually of type ViewResult. . The purpose of ViewData is so basic that I donβt think this is a problem, so I think that something is wrong with Rhino or MVCcontrib combined with MVC 3.
I also have the following test written earlier for the same controller action:
[Test] public void ShouldDisplayAListOfTodoItems() { Assert.That(((ViewResult)new TodoController().Index()).ViewData.Model, Is.EqualTo(Todo.ThingsToBeDone)); }
Now this fails with System.NullReferenceException : Object reference not set to an instance of an object , possibly because the HttpContext is not configured for this particular test. When you delete a ViewBag everything is fine.
We hope that the problem will become more clear.
Edit 2
When debugging code after deleting the ViewData.Model destination, it throws another error: System.NullReferenceException : Object reference not set to an instance of an object. in assigning a ViewBag .