相关疑难解决方法(0)

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

我正在尝试将单元测试添加到我构建的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)

c# unit-testing mocking httpcontext

171
推荐指数
4
解决办法
12万
查看次数

标签 统计

c# ×1

httpcontext ×1

mocking ×1

unit-testing ×1