How do you mock the session object collection using Moq

前端 未结 7 639
忘了有多久
忘了有多久 2020-11-28 22:08

I am using shanselmann\'s MvcMockHelper class to mock up some HttpContext stuff using Moq but the issue I am having is being able to assign something to my mocked session ob

7条回答
  •  眼角桃花
    2020-11-28 22:32

    I started with Scott Hanselman's MVCMockHelper, added a small class and made the modifications shown below to allow the controller to use Session normally and the unit test to verify the values that were set by the controller.

    /// 
    /// A Class to allow simulation of SessionObject
    /// 
    public class MockHttpSession : HttpSessionStateBase
    {
        Dictionary m_SessionStorage = new Dictionary();
    
        public override object this[string name]
        {
            get { return m_SessionStorage[name]; }
            set { m_SessionStorage[name] = value; }
        }
    }
    
    //In the MVCMockHelpers I modified the FakeHttpContext() method as shown below
    public static HttpContextBase FakeHttpContext()
    {
        var context = new Mock();
        var request = new Mock();
        var response = new Mock();
        var session = new MockHttpSession();
        var server = new Mock();
    
        context.Setup(ctx => ctx.Request).Returns(request.Object);
        context.Setup(ctx => ctx.Response).Returns(response.Object);
        context.Setup(ctx => ctx.Session).Returns(session);
        context.Setup(ctx => ctx.Server).Returns(server.Object);
    
        return context.Object;
    }
    
    //Now in the unit test i can do
    AccountController acct = new AccountController();
    acct.SetFakeControllerContext();
    acct.SetBusinessObject(mockBO.Object);
    
    RedirectResult results = (RedirectResult)acct.LogOn(userName, password, rememberMe, returnUrl);
    Assert.AreEqual(returnUrl, results.Url);
    Assert.AreEqual(userName, acct.Session["txtUserName"]);
    Assert.IsNotNull(acct.Session["SessionGUID"]);
    

    It's not perfect but it works enough for testing.

提交回复
热议问题