Sachin Maharjan
Sachin Maharjan

Reputation: 181

How can I test MVC Views?

My Page has following Hidden Field

<%= Html.Hidden("SessionId", Model.Form.UniqueSessionId) %>

My Controller

public class SomeController 
{
    public ActionResult Index()
    {
        var somemode = new GetSomeModel();
        return View(somemodel);
    }
}

I wanna be able to test whether the view has the hidden field

protected SomeController controller;

protected void SetupController()
{
   controller = new SomeController()
}

[Test]
public void view_has_hidden_field_for_SessionId()
{
    ViewResult result = controller.Index() as ViewResult;
    Assert.IsTrue(result.contains("<input type="hidden" id="SessionId" />"));
}

Question is: How can i render view as string? Any help?

Upvotes: 5

Views: 1709

Answers (1)

Dev Rios
Dev Rios

Reputation: 43

Take a look at this solution which has support for razor views and standard asp.net views:

Render a view as a string

My other advice to you would be to use an html parser such as HtmlAgilityPack so that you can then query it to find your hidden field. This approach is better as testing for string.contains will make your tests brittle when you refactor your html.

Upvotes: 2

Related Questions