Problem with TempData and Faked HttpContext using ASP.NET MVC

I am working with a fake HttpContext (the code is presented at the end), and I am probably missing something because I cannot access the TempData collection (fourth line of the SetFakeControllerContext method). Every time I try, I get this error message:

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

Code calling FakeHttpContext:

    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 anyone know what I'm 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;

}

Ps: I use Moq

UPDATE

OMG !! I CAN’T BELIEVE! More than 2 hours to understand that the problem was a link to the wrong MVC DLL. I referenced System.Web.Mvc 2.0 for my main application, but System.Web.Mvc 1.0 in another project. Sorry for this!

+3
1

- . TempData unit test. :

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"]);
    }
}
+4

Source: https://habr.com/ru/post/1767931/


All Articles