相关疑难解决方法(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万
查看次数

使用嵌套托管将 MVC5 视图作为字符串获取

我有以下由 Hangfire 执行的代码(没有 HttpContext),当我在本地运行时运行完美:

class FakeController : ControllerBase
{
    protected override void ExecuteCore() { }

    public static string RenderViewToString(string controllerName, string viewName, object viewData)
    {
        using (var writer = new StringWriter())
        {
            var routeData = new RouteData();
            routeData.Values.Add("controller", controllerName);
            var fakeControllerContext = new ControllerContext(
                                                              new HttpContextWrapper(
                                                                                     new HttpContext(new HttpRequest(null, "http://nopage.no", null)
                                                                                                   , new HttpResponse(null))
                                                                                     ), 
                                                              routeData, 
                                                              new FakeController()
                                                            );
            var razorViewEngine = new RazorViewEngine();
            var razorViewResult = razorViewEngine.FindView(fakeControllerContext, viewName, "", false);

            var viewContext = new ViewContext(fakeControllerContext, razorViewResult.View, new ViewDataDictionary(viewData), new …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc-5

5
推荐指数
1
解决办法
106
查看次数

标签 统计

c# ×2

asp.net-mvc-5 ×1

httpcontext ×1

mocking ×1

unit-testing ×1