Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 782
Sachin Maharjan Avatar asked Nov 02 '22 17:11

Sachin Maharjan


1 Answers

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.

like image 152
Dev Rios Avatar answered Nov 15 '22 06:11

Dev Rios