如何在单元测试中模拟控制器上下文,以便我的RenderViewToString方法有效? [英] How do I mock controller context in my unit test so that my RenderViewToString method works?

查看:89
本文介绍了如何在单元测试中模拟控制器上下文,以便我的RenderViewToString方法有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public static string RenderViewToString(ControllerContext context, string viewPath, object model = null, bool partial = false)
    {
        // first find the ViewEngine for this view
        ViewEngineResult viewEngineResult = null;
        if (partial)
            viewEngineResult = ViewEngines.Engines.FindPartialView(context, viewPath);
        else
            viewEngineResult = ViewEngines.Engines.FindView(context, viewPath, null);

        if (viewEngineResult == null)
            throw new FileNotFoundException("View not found.");

        // get the view and attach the model to view data
        var view = viewEngineResult.View;
        context.Controller.ViewData.Model = model;

        string result = null;
        using (var sw = new StringWriter())
        {
            var ctx = new ViewContext(context, view, context.Controller.ViewData, context.Controller.TempData, sw);
            view.Render(ctx, sw);
            result = sw.ToString();
        }
        return result;

    }







我想测试这个方法,但我不是能够根据需要构建/模拟ControllerContext。任何人都可以帮忙吗?




I want to Test this method but i am not able to build/Mock ControllerContext as required for it. Can anyone help for it?

推荐答案

这篇关于如何在单元测试中模拟控制器上下文,以便我的RenderViewToString方法有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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