其他分享
首页 > 其他分享> > CodeGo.net>在NUnit测试上使用moq模拟HttpContext.Current

CodeGo.net>在NUnit测试上使用moq模拟HttpContext.Current

作者:互联网

我正在测试一个MVC 3控制器,该控制器在此类上调用方法:

public class SessionVar
{
    /// <summary>
    /// Gets the session.
    /// </summary>
    private static HttpSessionState Session
    {
        get
        {
            if (HttpContext.Current == null)
                throw new ApplicationException
                                   ("No Http Context, No Session to Get!");

            return HttpContext.Current.Session;
        }
    }

    public static T Get<T>(string key)
    {
        return Session[key] == null ? default(T) : (T)Session[key];
    }
    ...
}

根据Hanselman’s Blog的建议,我的测试方法是:

[Test]
public void CanRenderEmployeeList()
{
    _mockIEmployeeService.Setup(s => s.GetEmployees(StatusFilter.OnlyActive))
        .Returns(BuildsEmployeeList().Where(e => e.IsApproved));

    var httpContext = FakeHttpContext();
    var target = _employeeController;
    target.ControllerContext = new ControllerContext
                  (new RequestContext(httpContext, new RouteData()), target);
    var result = target.Index();

    Assert.IsNotNull(result);
    Assert.IsInstanceOf<ViewResult>(result);
    var viewModel = target.ViewData.Model;
    Assert.IsInstanceOf<EmployeeListViewModel>(viewModel);
}

public static HttpContextBase FakeHttpContext()
{
    var context = new Mock<HttpContextBase>();
    var request = new Mock<HttpRequestBase>();
    var response = new Mock<HttpResponseBase>();
    var session = new Mock<HttpSessionStateBase>();
    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.Object);
    context.Setup(ctx => ctx.Server).Returns(server.Object);

    return context.Object;
}

但是我的测试一直失败,我得到:

CanRenderEmployeeListSystem.ApplicationException : No Http Context, 
                                                          No Session to Get!

这是HttpContext.Current == null时抛出的异常消息

我只需要Session对象“存在”,而不是存储在Session中的实际值.

你能告诉我我在做什么错吗?

谢谢.

解决方法:

从长远来看,如果您为SessionVar类创建一个接口,您会更快乐.在运行时使用当前的实现(通过Dependency Injection).在测试期间插入模拟.无需模拟所有这些Http运行时依赖项.

标签:nunit,moq,c,asp-net-mvc-3
来源: https://codeday.me/bug/20191031/1978390.html