据我了解,您想要做的是实际渲染视图,获取 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.)
}