在测试初始化​​方法中模拟HttpContext.Current

nfp*_*lee 171 c# unit-testing mocking httpcontext

我正在尝试将单元测试添加到我构建的ASP.NET MVC应用程序中.在我的单元测试中,我使用以下代码:

[TestMethod]
public void IndexAction_Should_Return_View() {
    var controller = new MembershipController();
    controller.SetFakeControllerContext("TestUser");

    ...
}
Run Code Online (Sandbox Code Playgroud)

使用以下帮助程序来模拟控制器上下文:

public static class FakeControllerContext {
    public static HttpContextBase FakeHttpContext(string username) {
        var context = new Mock<HttpContextBase>();

        context.SetupGet(ctx => ctx.Request.IsAuthenticated).Returns(!string.IsNullOrEmpty(username));

        if (!string.IsNullOrEmpty(username))
            context.SetupGet(ctx => ctx.User.Identity).Returns(FakeIdentity.CreateIdentity(username));

        return context.Object;
    }

    public static void SetFakeControllerContext(this Controller controller, string username = null) {
        var httpContext = FakeHttpContext(username);
        var context = new ControllerContext(new RequestContext(httpContext, new RouteData()), controller);
        controller.ControllerContext = context;
    }
}
Run Code Online (Sandbox Code Playgroud)

此测试类继承自具有以下内容的基类:

[TestInitialize]
public void Init() {
    ...
}
Run Code Online (Sandbox Code Playgroud)

在这个方法里面它调用一个库(我无法控制),它试图运行以下代码:

HttpContext.Current.User.Identity.IsAuthenticated
Run Code Online (Sandbox Code Playgroud)

现在您可以看到问题所在.我已经针对控制器设置了假的HttpContext,但是没有在这个基本的Init方法中.单元测试/嘲笑对我来说很新,所以我想确保我做对了.对我来说,模拟HttpContext的正确方法是什么,以便在我的控制器和我的Init方法中调用的任何库之间共享它.

Ric*_*lay 350

HttpContext.Current返回一个System.Web.HttpContext不扩展的实例System.Web.HttpContextBase.HttpContextBase后来被添加以解决HttpContext难以模拟的问题.这两个类基本上不相关(HttpContextWrapper用作它们之间的适配器).

幸运的是,HttpContext它本身就是假的,足以让你替换IPrincipal(用户)和IIdentity.

即使在控制台应用程序中,以下代码也按预期运行:

HttpContext.Current = new HttpContext(
    new HttpRequest("", "http://tempuri.org", ""),
    new HttpResponse(new StringWriter())
    );

// User is logged in
HttpContext.Current.User = new GenericPrincipal(
    new GenericIdentity("username"),
    new string[0]
    );

// User is logged out
HttpContext.Current.User = new GenericPrincipal(
    new GenericIdentity(String.Empty),
    new string[0]
    );
Run Code Online (Sandbox Code Playgroud)

  • @nfplee - 如果将空字符串传递给`GenericIdentity`构造函数,`IsAuthenticated`将返回false (5认同)
  • @CiaranG - MVC使用`HttpContextBase`,可以模拟.如果您使用的是MVC,则无需使用我发布的解决方法.如果你继续使用它,你可能需要在你甚至_create_控制器之前运行我发布的代码. (4认同)
  • 这可以用来模拟HttpContext中的Cache吗? (2认同)

PUG*_*PUG 32

Test Init也将完成这项工作.

[TestInitialize]
public void TestInit()
{
  HttpContext.Current = new HttpContext(new HttpRequest(null, "http://tempuri.org", null), new HttpResponse(null));
  YourControllerToBeTestedController = GetYourToBeTestedController();
}
Run Code Online (Sandbox Code Playgroud)

  • @ user1522548(你应该创建一个帐户)程序集System.Web.dll,v4.0.0.0肯定有HTTPContext我刚检查了我的源代码. (2认同)

小智 6

如果您的应用程序第三方内部重定向,那么最好通过以下方式模拟 HttpContext :

HttpWorkerRequest initWorkerRequest = new SimpleWorkerRequest("","","","",new StringWriter(CultureInfo.InvariantCulture));
System.Web.HttpContext.Current = new HttpContext(initWorkerRequest);
System.Web.HttpContext.Current.Request.Browser = new HttpBrowserCapabilities();
System.Web.HttpContext.Current.Request.Browser.Capabilities = new Dictionary<string, string> { { "requiresPostRedirectionHandling", "false" } };
Run Code Online (Sandbox Code Playgroud)


agg*_*ton 5

我知道这是一门比较老的主题,但是我们非常定期地模拟MVC应用程序进行单元测试。

我只是想添加我的经验,升级到Visual Studio 2013之后,使用Moq 4模拟MVC 3应用程序。没有任何单元测试在调试模式下工作,并且HttpContext在尝试查看变量时显示“无法评估表达式” 。

事实证明,Visual Studio 2013在评估某些对象方面存在问题。为了使调试的模拟Web应用程序再次运行,我必须在Tools => Options => Debugging => General设置中检查“ Use Managed Compatibility Mode”。

我通常会这样做:

public static class FakeHttpContext
{
    public static void SetFakeContext(this Controller controller)
    {

        var httpContext = MakeFakeContext();
        ControllerContext context =
        new ControllerContext(
        new RequestContext(httpContext,
        new RouteData()), controller);
        controller.ControllerContext = context;
    }


    private static HttpContextBase MakeFakeContext()
    {
        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>();
        var user = new Mock<IPrincipal>();
        var identity = new Mock<IIdentity>();

        context.Setup(c=> c.Request).Returns(request.Object);
        context.Setup(c=> c.Response).Returns(response.Object);
        context.Setup(c=> c.Session).Returns(session.Object);
        context.Setup(c=> c.Server).Returns(server.Object);
        context.Setup(c=> c.User).Returns(user.Object);
        user.Setup(c=> c.Identity).Returns(identity.Object);
        identity.Setup(i => i.IsAuthenticated).Returns(true);
        identity.Setup(i => i.Name).Returns("admin");

        return context.Object;
    }


}
Run Code Online (Sandbox Code Playgroud)

并像这样启动上下文

FakeHttpContext.SetFakeContext(moController);
Run Code Online (Sandbox Code Playgroud)

并直接在控制器中调用方法

long lReportStatusID = -1;
var result = moController.CancelReport(lReportStatusID);
Run Code Online (Sandbox Code Playgroud)