ASP.NET MVC2 - Render a View as a String

2020-07-25 09:09发布

问题:

How do you render a view as a string from a controller in MVC 2?

In MVC 1, I used CaptureActionHtml. I'm having the same problem with it as a similar question, but is there a way to do this without Rhink.Mocks?

回答1:

I've found Steve Sanderson's Integration Testing framework to work out very well for this.

Perusing one of the code samples from his own blog post gives you some idea of the capabilities of the framework, the assertions that you can perform against its output, etc:

[Test]
public void Root_Url_Renders_Index_View()
{
    appHost.SimulateBrowsingSession(browsingSession => {
        // Request the root URL
        RequestResult result = browsingSession.ProcessRequest("/");

        // You can make assertions about the ActionResult...
        var viewResult = (ViewResult) result.ActionExecutedContext.Result;
        Assert.AreEqual("Index", viewResult.ViewName);
        Assert.AreEqual("Welcome to ASP.NET MVC!", viewResult.ViewData["Message"]);

        // ... or you can make assertions about the rendered HTML
        Assert.IsTrue(result.ResponseText.Contains("<!DOCTYPE html"));
    });
}