2016-08-22 237 views
2

我有兩個單元測試和Web項目項目。使用Cookie進行MVC單元測試

 AuthenticationController controller = new AuthenticationController(); 
     ViewResult result = controller.LogOut() as ViewResult; 
     Assert.IsNotNull(result); 

在項目中,我會傳遞http cookie和授權請求。

當我運行LogOut測試時,它會在獲取cookie時失敗。有沒有辦法通過創建一個假的cookie或任何其他方式來克服這個問題?

在此先感謝。

+0

看一看這個答案:http://stackoverflow.com/questions/18098585/moq-mocking-mvc-controllers-response-cookies-clear/18101855#18101855 –

+0

顯示LogOut'的'實施 – Nkosi

回答

1

希望這有助於!或者使用模擬框架。

AuthenticationController controller = new AuthenticationController(); 
var httpContext = new MockHttpContext(); 
//set cookie 

controller.ControllerContext = new ControllerContext(httpContext, controller); 

public class MockHttpContext : HttpContextBase 
{ 
    readonly HttpRequestBase _request; 

    public MockHttpContext() 
    { 
     _request = new MockHttpRequest(); 
    } 

    public override HttpRequestBase Request 
    { 
     get { return _request; } 
    } 

    class MockHttpRequest : HttpRequestBase 
    { 
     readonly HttpCookieCollection _cookies; 

     public MockHttpRequest() 
     { 
      _cookies = new HttpCookieCollection(); 
     } 

     public override HttpCookieCollection Cookies 
     { 
      get 
      { 
       return _cookies; 
      } 
     } 
    } 
}