I have an HTMLHelper extension method that outputs HTML to Response.Write. How best to unit test this?
I'm considering mocking the HtmlHelper passed into the method, but am unsure as to how I should verify the HTML sent to Response.Write.
Thanks
If you are using an HTML helper to output text to the browser why not have it return a string and in your view do something like ...
<%=Html.YourExtension() %>
It makes it a great deal more testable.
Kindness,
Dan
EDIT:
Modification would be a change of signature
public static void YourExtension(this HtmlHelper html)
{
...
Response.Write(outputSting);
}
to
public static string YourExtension(this HtmlHelper html)
{
...
return outputSting;
}
I use the following code to test and validate html helpers. If you are doing anything complex, like disposable based helpers like beginform or helpers with dependencies you need a better test framework then just looking at the string of a single helper.
Validation is a another example.
Try the following:
var sb = new StringBuilder();
var context = new ViewContext();
context.ViewData = new ViewDataDictionary(_testModel);
context.Writer = new StringWriter(sb);
var page = new ViewPage<TestModel>();
var helper = new HtmlHelper<TestModel>(context, page);
//Do your stuff here to exercise your helper
//Get the results of all helpers
var result = sb.ToString();
//Asserts and string tests here for emitted HTML
Assert.IsNotNullOrEmpty(result);
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