如何使用 Moq 在 ASP.NET MVC 中模拟 HttpContext? [英] How do I mock the HttpContext in ASP.NET MVC using Moq?

查看:32
本文介绍了如何使用 Moq 在 ASP.NET MVC 中模拟 HttpContext?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[TestMethod]
public void Home_Message_Display_Unknown_User_when_coockie_does_not_exist()
{
    var context = new Mock<HttpContextBase>();
    var request = new Mock<HttpRequestBase>();
    context
        .Setup(c => c.Request)
        .Returns(request.Object);
    HomeController controller = new HomeController();

    controller.HttpContext = context; //Here I am getting an error (read only).
    ...
 }

我的基本控制器覆盖了获取此 requestContext 的 Initialize.我试图传递这个,但我没有做正确的事情.

my base controller has an overrride of the Initialize that get's this requestContext. I am trying to pass this along but I am not doing something right.

protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
    base.Initialize(requestContext);
}

从哪里可以获得有关使用 Moq 模拟 RequestContext 和 HttpContext 的更多信息?我正在尝试模拟 cookie 和一般上下文.

Where can I get more information on mocking my RequestContext and HttpContext using Moq? I am trying to mock cookies and the general context.

推荐答案

HttpContext 是只读的,但实际上是从 ControllerContext 派生出来的,可以设置.

HttpContext is read-only, but it is actually derived from the ControllerContext, which you can set.

 controller.ControllerContext = new ControllerContext( context.Object, new RouteData(), controller );

这篇关于如何使用 Moq 在 ASP.NET MVC 中模拟 HttpContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆