I am trying out the MVC3 Razor view engine, and one the features that I am exploring is the ability to unit test views.
I have seen a number of examples where Razor views can be compiled into an assembly and rendered into a string. The problem is that it renders as a string, so I am left with doing string searches!
Here is what I am trying to do.
The reason that I want to do this is so that I can test for specific parts of the output. The helper will likely spit out HTML that includes various output gunk. What I want to do is to see if there is a Checkbox with a particular value (for example). If you have seen Selenium tests, it is similar to what I would like to do, except not as server driven tests.
Is there some way to get compiled Razor (or other view engine) views to emit something other than strings?
The short answer is no, because view engines' purpose in life is to spit out strings. Parsing those strings into an XML document is a way to give them a little structure, like @Craig-M suggested. But what you have to ask yourself is what you're really testing. If your view compiles and generates some kind of HTML, there can be three problems with what it generated:
That last one would be very nice to test for, but why not test for it in javascript unit tests? Check out popular javascript unit test suites like JsUnit, FireUnit, QUnit, etc. They would all do a much better job than you could do of parsing out Razor output.
I think the value assigned to a checkbox would probably be tested for in Controller testing. But to use your example, testing your checkbox's value could be $('#theCheck').val() == 'the value'. And you can run these against a website running with dependency injected repositories or services to control things like 'the value'.
Just a thought.
One way you could go about this is to parse the html string into an XDocument and have your assembly return it. Then you can query against it with LINQ in your tests.
Edit: I'm trying to figure out a Razor test strategy too. I'd be interested to know how you get the helper to work. So far, I'm drawing a blank in getting them rendered to strings outside of the MVC framework.
How about rendering your views to html and then sending that html to HtmlAgility library? That way you can easily traverse/navigate your html. I don't think there is any way to do that with MVC itself.
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