2014-03-05 85 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如果你還沒有問過,那麼你最好問個別問題。 –

相關問題