2009-02-25 65 views
4

我試圖利用asp.net mvc rc1中的recent ControllerContext refactoring。我應該能而不是簡單地存根的會議,但我一直運行下面的代碼時,第2行得到一個System.NullReferenceException:如何使用rhino mocks在MVC RC1中存儲HttpSessionState?

var mockContext = MockRepository.GenerateStub<ControllerContext>(); 
mockContext.Stub(x => x.HttpContext.Session["MyKey"]).Return("MyValue"); 

我在做什麼錯?

編輯:我剛剛證實我有這個職位的最新版本的犀牛。

回答

6

你也需要模擬HttpContext來使這個工作。 我使用的HttpContext的模擬這個:

public class HttpContextMock 
{ 
    private readonly HttpContextBase _contextBase; 
    private readonly HttpRequestBase _requestBase; 
    private readonly HttpResponseBase _responseBase; 
    private readonly HttpSessionStateBase _sessionStateBase; 
    private readonly HttpServerUtilityBase _serverUtilityBase; 

    public HttpContextBase Context { get { return _contextBase; } } 
    public HttpRequestBase Request { get { return _requestBase; } } 
    public HttpResponseBase Response { get { return _responseBase; } } 
    public HttpSessionStateBase Session { get { return _sessionStateBase; } } 
    public HttpServerUtilityBase Server { get { return _serverUtilityBase; } } 


    public HttpContextMock() 
    { 
     _contextBase = MockRepository.GenerateStub<HttpContextBase>(); 
     _requestBase = MockRepository.GenerateStub<HttpRequestBase>(); 
     _responseBase = MockRepository.GenerateStub<HttpResponseBase>(); 
     _sessionStateBase = MockRepository.GenerateStub<HttpSessionStateBase>(); 
     _serverUtilityBase = MockRepository.GenerateStub<HttpServerUtilityBase>(); 

     _contextBase.Stub(x => x.Request).Return(_requestBase); 
     _contextBase.Stub(x => x.Response).Return(_responseBase); 
     _contextBase.Stub(x => x.Session).Return(_sessionStateBase); 
     _contextBase.Stub(x => x.Server).Return(_serverUtilityBase); 

     _requestBase.Stub(x => x.IsAuthenticated).Return(true); 

     _contextBase.User = new GenericPrincipal(new GenericIdentity("[email protected]"), 
               new string[] {"Admin"}); 

    } 
} 

而且在測試設置I創建一個控制器的實例:

[SetUp] 
    public override void TestSetUp() 
    { 
     base.TestSetUp(); 

     repository = MockRepository.GenerateMock<IFooRepository>(); 
     controller = new FooController() 
         { 
          FooRepository = repository, 
          UserRepository = userMockRepository 
         }; 

     controller.ControllerContext = new ControllerContext(context.Context, new RouteData(), controller); 
    } 

和所有工作正常,我可以參數添加到會議和其他許多事情。 希望這有助於。