asp.net mvc如何在单元测试中使用session

在单元测试中我们如果遇到需要使用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;
}

asp.net mvc如何在单元测试中使用session

上一篇:PHP设计模式-简单工厂模式


下一篇:css 选择器种类 10种 + 权重