如何在Moq框架中模拟HttpContext(ControllerContext)并进行会话

Omi*_*ati 5 c# asp.net-mvc moq mocking httpcontext

我想测试我的MVC应用程序,并且想模拟HttpContext。我正在使用Moq框架,这是我模拟HttpContext所做的工作:

[SetUp]
public void Setup()
{
    MyUser myUser = new MyUser();
    myUser.Id = 1;
    myUser.Name = "AutomatedUITestUser";

    var fakeHttpSessionState = 
                         new FakeHttpSessionState(new SessionStateItemCollection());
    fakeHttpSessionState.Add("__CurrentUser__", myUser);

    ControllerContext mockControllerContext = Mock.Of<ControllerContext>(ctx =>
        ctx.HttpContext.User.Identity.Name == myUser.Name &&
        ctx.HttpContext.User.Identity.IsAuthenticated == true &&
        ctx.HttpContext.Session == fakeHttpSessionState &&
        ctx.HttpContext.Request.AcceptTypes == 
                       new string[]{ "MyFormsAuthentication" } &&
        ctx.HttpContext.Request.IsAuthenticated == true &&
        ctx.HttpContext.Request.Url == new Uri("http://moqthis.com") &&
        ctx.HttpContext.Response.ContentType == "application/xml");

    _controller = new SomeController();
     _controller.ControllerContext = mockControllerContext; //this line is not working
    //when I see _controller.ControllerContext in watch, it get's me 
    //_controller.ControllerContext threw an exception of type System.ArgumentException
}

[Test]
public void Test_ControllerCanDoSomething()
{
    // testing an action of the controller
    // The problem is, here, System.Web.HttpContext.Current is null
}
Run Code Online (Sandbox Code Playgroud)

因为我的应用程序几乎在每个操作方法中都使用Session来保存用户数据和身份验证信息,所以我需要在会话中HttpContext设置会话Session并将其放入__CurrentUser__会话中,以便操作方法可以访问伪造的登录用户。

但是,HttpContext未设置,它为null。我搜索了很多东西,但找不到答案。可能是什么问题?

更新: 我也测试下面的行,并得到相同的结果

_controller.ControllerContext = new ControllerContext(
                       mockControllerContext.HttpContext, new RouteData(), _controller);
Run Code Online (Sandbox Code Playgroud)

Ale*_*ith 3

从这个答案来看:Mocking Asp.net-mvc Controller Context

看起来您需要模拟请求本身以及请求对象的属性。

例如

var request = new Mock<HttpRequestBase>();
Run Code Online (Sandbox Code Playgroud)

等(完整的代码位于链接的答案中)。