gpt4 book ai didi

asp.net-mvc - 通过以编程方式执行 Controller (使用 RouteData)来捕获 Action 的结果

转载 作者:行者123 更新时间:2023-12-02 04:58:39 25 4
gpt4 key购买 nike

我从 Darin Dimitrov 那里找到了以下答案 - In ASP MVC3, how can execute a controller and action using a 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 的属性中的某处找到结果,但我找不到类似的东西。有谁知道如何做到这一点?

最佳答案

据我所知,你想要做的是实际呈现 View ,获取 HTML 结果并对其进行断言。

这实际上是在测试几乎不推荐和反对大多数实践的 View 。

但是,您可以想出一些解决方案。所呈现的(简化且有点困惑)是使用 RazorEngine 来渲染 View 。由于您无法从测试项目访问 .cshtml( View 文件),因此您需要以一种困惑的方式获取其内容。

将 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.)
}

关于asp.net-mvc - 通过以编程方式执行 Controller (使用 RouteData)来捕获 Action 的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19090331/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com