2014-03-05 56 views
4

我想测试我的MVC应用程序,并且我想模拟HttpContext。我使用起订量框架,这里是我做了什么,以模拟的HttpContext:如何在Moq框架中模拟HttpContext(ControllerContext),并有会话

[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 
} 

因为我的应用程序使用会议持有几乎所有的操作方法,用户数据和身份验证信息,因此,我需要设置HttpContext,在它内部我需要设置Session并将__CurrentUser__放在会话中,以便操作方法可以访问伪造的登录用户。

但是,HttpContext没有设置,它是空的。我搜索了很多,我找不到我的答案。 什么可能是错误的?

更新: 我也考验下方线,并得到相同的结果

_controller.ControllerContext = new ControllerContext(
         mockControllerContext.HttpContext, new RouteData(), _controller); 
+0

可能重复[如何使用Moq模拟ASP.NET MVC中的HttpContext?](http://stackoverflow.com/questions/1452418/how-do-i-mock-the-httpcontext-in-asp -net-mvc-using-moq) –

+0

Microsoft建议在代码中使用HttpContextWrapper,以便稍后对单元测试进行更简单的处理.http://msdn.microsoft.com/en-us/library/system.web.httpcontextwrapper(v = vs.110).aspx –

+0

谢谢@MikeCheel但我的问题不同,我没有设置HttpContext而不是ControllerContext,我的问题是我无法设置ControllerContext!任何人都可以回答我的qiestion吗? –

回答

3

通过这样的回答来看:Mocking Asp.net-mvc Controller Context

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

例如

var request = new Mock<HttpRequestBase>(); 

等(完整的代码在链接的答案)。

+0

如何在WebApi中模拟System.Web.HttpRequest(Form)? – Dave

+0

嗨@Dave如果你还没有问过,那么你最好问个别问题。 –

相关问题