3

我从 Darin Dimitrov 那里找到了以下答案——在 ASP MVC3 中,如何使用 uri 执行控制器和操作?

var routeData = new RouteData();
// controller and action are compulsory
routeData.Values["action"] = "index";
routeData.Values["controller"] = "foo";
// some additional route parameter
routeData.Values["foo"] = "bar";
IController fooController = new FooController();
var rc = new RequestContext(new HttpContextWrapper(HttpContext), routeData);
fooController.Execute(rc);

唯一的问题是我喜欢捕获此 Action 返回的 ViewResult(以将其呈现为字符串),但 IController.Execute 返回void

我怀疑我可以在 ControllerContext 的属性中的某处找到结果,但我找不到类似的东西。有谁知道如何做到这一点?

4

1 回答 1

0

据我了解,您想要做的是实际渲染视图,获取 HTML 结果并针对它进行断言。

这实际上是在测试几乎不推荐并且针对大多数实践的视图。

但是,您可以为此提出一些解决方案。呈现的一个(简化且有点混乱)是使用 RazorEngine 来呈现视图。由于您无法从测试项目中访问 .cshtml(视图文件),因此您需要以混乱的方式访问其内容。

将 RazorEngine NuGet 包安装到您的测试项目并尝试以下方式:

    [Fact]
    public void Test()
    {
        var x = new HomeController();  // instantiate controller
        var viewResult = (ViewResult)x.Index(); // run the action and obtain its ViewResult
        var view = string.IsNullOrWhiteSpace(viewResult.ViewName) ? "Index" : viewResult.ViewName;     // get the resulted view name; if it's null or empty it means it is the same name as the action
        var controllerName = "Home"; // the controller name was known from the beginning

        // actually navigate to the folder containing the views; in this case we're presuming the test project is a sibling to the MVC project, otherwise adjust the path to the view accordingly
        var pathToView = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase).Replace("file:\\", "");
        pathToView = Path.GetDirectoryName(pathToView);
        pathToView = Path.GetDirectoryName(pathToView);
        pathToView = Path.GetDirectoryName(pathToView);
        pathToView = Path.Combine(pathToView, "WebApplication5\\Views\\" + controllerName + "\\" + view + ".cshtml");

        var html = Razor.Parse(File.ReadAllText(pathToView), viewResult.Model);  // this is the HTML result, assert against it (i.e. search for substrings etc.)
    }
于 2016-07-07T12:02:45.867 回答