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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With