Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

How can I get generated HTML (View) in my Test Method?

I have the following:

Controller:

public ActionResult Index()
{
    ViewBag.Message = "Welcome to ASP.NET MVC!";

    return View();
}

View:

@{
    ViewBag.Title = "Home Page";
}

<h2>@ViewBag.Message</h2>
<p>
    To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
</p>

Test:

   [TestMethod]
    public void HomeControllerReturnsView()
    {
        // Arrange
        var controller = new HomeController();

        // Act
        var result = controller.Index() as ViewResult;

        using (StringWriter sw = new StringWriter())
        {
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, "Home");
            ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
            viewResult.View.Render(viewContext, sw);

            var test = sw.GetStringBuilder().ToString();
        }
    }

FYI: when i run this in debug controller.HttpContext and controller.RouteData are null. thanks

share|improve this question

closed as not a real question by tereško, dove, Matt Whipple, BNL, Florent Oct 31 '12 at 16:21

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.If this question can be reworded to fit the rules in the help center, please edit the question.

1 Answer

up vote 3 down vote accepted

You could use the RazorGenerator to execute the views inside the unit test. Here's a blog post in which David Ebbo illustrates this.

But those are no longer unit tests. They are integration tests and you could use tools such as Watin which could allow you to perform integration tests on your application.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.