惩戒HttpContext.Current使用上NUnit测试MOQ [英] Mocking HttpContext.Current using moq on NUnit Test

查看:296
本文介绍了惩戒HttpContext.Current使用上NUnit测试MOQ的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我测试的MVC 3控制器调用这个类的方法:

I am testing an MVC 3 controller that calls methods on this class:

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的博客建议是:

[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;
}



但我的测试不断失败,我得到:

But my test keeps failing, I get:

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



这是被抛出时, HttpContext.Current == NULL异常消息

我只需要Session对象'存在',而不是存储在会话中的实际值。

I just need the Session object to 'exist', not the actual values stored on the Session.

您可以告诉我,我究竟做错了什么?

Can you tell me what am I doing wrong?

感谢。

推荐答案

在从长远来看,如果你创建了SessionVar类的接口,你会更快乐。在运行时使用当前的实现(通过依赖注入)。在测试过程中插入一个模拟。移除嘲讽所有这些HTTP运行时依赖的需求。

In the long run, you'll be happier if you create an interface for the SessionVar class. Use your current implementation (via Dependency Injection) at runtime. Plug in a mock during testing. Removes the need for mocking out all of those Http runtime dependencies.

这篇关于惩戒HttpContext.Current使用上NUnit测试MOQ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆