风暴烈酒辰

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

在单元测试中我们如果遇到需要使用session的场景,可以使用Moq做如下处理:
创建一个类:MockHttpSession

public class MockHttpSession : HttpSessionStateBase
{
    Dictionary<string, object> m_SessionStorage = new Dictionary<string, object>();

    public override object this[string name]
    {
        get { return m_SessionStorage[name]; }
        set { m_SessionStorage[name] = value; }
    }
}

在测试中加入如下代码:

[TestMethod]
public void GetSilderCodeImage()
{
    var mock = new Mock<ControllerContext>();
    var mockSession = new MockHttpSession();
    mock.Setup(p => p.HttpContext.Session).Returns(mockSession);
    controller.ControllerContext = mock.Object;

    FileResult result = controller.GetSilderCodeImage() as FileResult;
    Assert.IsNotNull(result);
    Assert.IsNotNull(controller.Session["offsetX"]);
}

Moq还可以模拟各种HttpContext中的对象:

public static HttpContextBase FakeHttpContext()
{
    var context = new Mock<HttpContextBase>();
    var request = new Mock<HttpRequestBase>();
    var response = new Mock<HttpResponseBase>();
    var session = new MockHttpSession();
    var server = new Mock<HttpServerUtilityBase>();

    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;
}
posted on 2021-04-01 19:14  风暴烈酒辰  阅读(268)  评论(0编辑  收藏  举报