Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Get View HTML output in Test Method

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

like image 536
ShaneKm Avatar asked Dec 05 '25 19:12

ShaneKm


1 Answers

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.

like image 132
Darin Dimitrov Avatar answered Dec 07 '25 11:12

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!