Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with TempData and Faked HttpContext using ASP.NET MVC

I am working with a faked HttpContext (code provided in the end) and probably I am missing something because I can't access TempData collection (forth line of SetFakeControllerContext method). Every time I try I get this error message:

'controller.TempData' threw an exception of type 'System.AccessViolationException'

The code that calls FakeHttpContext is:

    public static void SetFakeControllerContext(this Controller controller)
    {
        HttpContextBase httpContext = FakeHttpContext(string.Empty);
        var context = new ControllerContext(new RequestContext(httpContext, new RouteData()), controller);
        controller.ControllerContext = context;
        controller.TempData = new TempDataDictionary(); //This is not necessary! It was just a test!!!!
    }

Does anybody know what I am doing wrong?

public static HttpContextBase FakeHttpContext(string username){

var context = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
var response = new Mock<HttpResponseBase>();
var session = new Mock<HttpSessionStateBase>();
var server = new Mock<HttpServerUtilityBase>();
var user = new Mock<IPrincipal>();
var identity = new Mock<IIdentity>();

context.Setup(ctx => ctx.Request).Returns(request.Object);
context.Setup(ctx => ctx.Response).Returns(response.Object);
context.Setup(ctx => ctx.Session).Returns(session.Object);
context.Setup(ctx => ctx.Server).Returns(server.Object);
context.Setup(ctx => ctx.User).Returns(user.Object);

user.Setup(ctx => ctx.Identity).Returns(identity.Object);

if (!string.IsNullOrEmpty(username))
{
    identity.Setup(id => id.IsAuthenticated).Returns(true);
    identity.Setup(id => id.Name).Returns(username);
}
else
{
    identity.Setup(id => id.IsAuthenticated).Returns(false);
    identity.Setup(id => id.Name).Returns(string.Empty);
}

context.Setup(ctx => ctx.Response.Cache).Returns(CreateCachePolicy());
return context.Object;

}

P.s.: I am using Moq

UPDATE:

OMG!! I CAN'T BELIEVE IT! More than 2 hours to figure out that the problem was a reference to the wrong MVC dll. I was referencing System.Web.Mvc 2.0 for my main app but System.Web.Mvc 1.0 in another project. Sorry about this!

like image 388
nepomucenobr Avatar asked Sep 13 '25 23:09

nepomucenobr


1 Answers

The problem's definitely somewhere else. You don't even need to initialize the TempData property to a new dictionary in your unit test. The following program works fine:

public class HomeController: Controller
{
    public ActionResult Index()
    {
        TempData["foo"] = "bar";
        return View();
    }
}

class Program
{
    static void Main()
    {
        var controller = new HomeController();
        controller.Index();
        Console.WriteLine(controller.TempData["foo"]);
    }
}
like image 175
Darin Dimitrov Avatar answered Sep 15 '25 13:09

Darin Dimitrov