Lars-Erik's bloghttp://blog.aabech.no/blog/
Ramblings about Umbraco, .net and JavaScript development. With a sprinkle of other stuff.Articulate, blogging built on Umbraco1126http://blog.aabech.no/archive/testing-views-with-razorgenerator/
unit testingTesting views with RazorGenerator<h2>Razor what?</h2>
<p>RazorGenerator is a hidden gem that lets you generate and pre-compile what would otherwise be generated and compiled at runtime. Your Razor. Not only does it give you a startup time boost, but it lets you unit test your views. The latter is the focus of this post.</p>
<p>We'll continue to build on the project I described in <a href="/archive/generating-documentation-from-nunit-tests/">my post on generating documentation with NUnit</a>. It's a simple use case where an imaginary CMS has a feature to display events from a third party site. Here are the tests I've got so far:</p>
<p><img src="http://blog.aabech.no/blog/media/1024/nunitoutput.png" alt="NUnit output" /></p>
<p>In my previous post, I left the rendering test inconclusive. I like keeping inconclusive tests around as reminders of stuff I've got left to do. Let's have a quick look at the passing code before we dive into the rendering bits.</p>
<h2>Basic HTTP integration and conversion tests</h2>
<p>The first large piece of what's in there for now is a way to remove the physical dependency on the third party site. I like to stub away IO as far out as I can so I can test as much of my code quickly, yet as integrated as possible. In other words, as many participating classes as possible. Since we're making an example here, I'm just using the <code>HttpClient</code> directly from the controller. The <code>HttpClient</code> is hard to mock or fake, but it has an inner dependency that we can pass as an argument to a constructor: <code>HttpMessageHandler</code>. It has the innermost function that the <code>HttpClient</code> uses for any operation. It also has the rare trait of being <code>protected virtual</code>, so we can stub it out. For this example, I'm just using a fake one that records requests and returns responses for registered URLs. Here it is:</p>
<pre><code>public class FakeMessageHandler : HttpMessageHandler
{
private readonly Dictionary&lt;string, string&gt; responses = new Dictionary&lt;string,string&gt;();
public List&lt;string&gt; Calls { get; } = new List&lt;string&gt;();
public void Register(string url, string response)
{
responses.Add(url, response);
}
protected override Task&lt;HttpResponseMessage&gt; SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var url = request.RequestUri.ToString();
Calls.Add(url);
if (!responses.ContainsKey(url))
{
return Task.FromResult(new HttpResponseMessage
{
StatusCode = HttpStatusCode.NotFound,
Content = new StringContent(&quot;{}&quot;)
});
}
return Task.FromResult(new HttpResponseMessage
{
Content = new StringContent(responses[url])
});
}
}
</code></pre>
<p>We'll not dwell further on this one in this post, but you'll need it to run the following examples if you want to tag along.</p>
<p>The tests that verifies that we call the right URL on the third party site is pretty simple. It checks the Calls collection on the FakeMessageHandler. Here's the test and the setup code needed:</p>
<pre><code>[TestFixture]
public class When_Displaying_An_Event
{
[Test]
[DocumentationOrder(0)]
[Description(@&quot;
Events are provided at eventsite with a REST api at the URL:
https://eventsite/api/{id}
&quot;)]
public void It_Is_Fetched_By_Id_From_The_Event_Server()
{
eventController.Event(234).Wait();
Assert.AreEqual(
&quot;https://eventsite/api/234&quot;,
httpMessageHandler.Calls.Single()
);
}
// ... omitted other tests
[SetUp]
public void Setup()
{
httpMessageHandler = new FakeMessageHandler();
httpClient = new HttpClient(httpMessageHandler);
eventController = new EventController(httpClient);
}
private FakeMessageHandler httpMessageHandler;
private HttpClient httpClient;
private EventController eventController;
}
</code></pre>
<p>And the controller:</p>
<pre><code>public class EventController : Controller
{
private readonly HttpClient httpClient;
public EventController(HttpClient httpClient)
{
this.httpClient = httpClient;
}
public async Task&lt;PartialViewResult&gt; Event(int id)
{
var requestUri = &quot;https://eventsite/api/&quot; + id;
var result = await httpClient.GetAsync(requestUri);
var response = await result.Content.ReadAsStringAsync();
// ... omitted further processing for now
}
}
</code></pre>
<p>We pass the <code>FakeMessageHandler</code> instance to a new <code>HttpClient</code> effectively making it a stub. We can control the response for individual URLs, and verify that the right ones were called.</p>
<p>Next step is to convert it to a valid model we can use in our view. We've got a second test asserting that:</p>
<pre><code>[Test]
[DocumentationOrder(1)]
[Description(&quot;The JSON response from the event server is deserialized as the Event type.&quot;)]
public void It_Is_Converted_To_An_Event_Model()
{
var result = GetConcertEvent();
var model = (Event)result.Model;
Assert.AreEqual(&quot;Concert of your life&quot;, model.Name);
Assert.AreEqual(new DateTime(2049,12,31,23,59,59), model.Time);
Assert.AreEqual(&quot;https://eventsite/123&quot;, model.Url);
}
private PartialViewResult GetConcertEvent()
{
httpMessageHandler.Register(
&quot;https://eventsite/api/123&quot;,
&quot;{\&quot;name\&quot;:\&quot;Concert of your life\&quot;, \&quot;time\&quot;:2524607999}&quot;
);
var result = eventController.Event(123).Result;
return result;
}
</code></pre>
<p>And here's the rest of the controller code creating that model:</p>
<pre><code>public async Task&lt;PartialViewResult&gt; Event(int id)
{
var requestUri = &quot;https://eventsite/api/&quot; + id;
var result = await httpClient.GetAsync(requestUri);
var response = await result.Content.ReadAsStringAsync();
var eventJObj = JsonConvert.DeserializeObject&lt;JObject&gt;(response);
var evt = new Event
{
Name = eventJObj.Value&lt;string&gt;(&quot;name&quot;),
Time = DateTimeOffset.FromUnixTimeSeconds(eventJObj.Value&lt;long&gt;(&quot;time&quot;)).DateTime,
Url = &quot;https://eventsite/&quot; + id
};
return PartialView(&quot;Event&quot;, evt);
}
</code></pre>
<p>The test is a tedious verification of every property on the event object. There are several ways to get around that. Amongst others, equality members. I've got a way better trick, but that's for an upcoming post.</p>
<p>Now that we're through those tests, let's dive into how we can test the actual HTML output of this whole shenanigan.</p>
<h2>Generating some Razor</h2>
<p>As mentioned initially, RazorGenerator is a hidden gem in the ASP.NET OSS wilderness. There's a Visual Studio plugin that you need to exploit it fully. It's aptly called RazorGenerator and <a href="https://marketplace.visualstudio.com/items?itemName=DavidEbbo.RazorGenerator">can be installed from here</a>. There's also a couple of Nuget packages that we want:</p>
<ul>
<li><a href="https://www.nuget.org/packages/RazorGenerator.Mvc/">RazorGenerator.Mvc</a><br />
Referenced in your website to make use of a special <code>ViewEngine</code> for pre-compiled views.</li>
<li><a href="https://www.nuget.org/packages/RazorGenerator.Testing/">RazorGenerator.Testing</a><br />
Referenced in our test projects to be able to automagically render views in tests.</li>
</ul>
<p>Armed with these tools, there's nothing left to do but add a custom tool to our view:</p>
<p><img src="http://blog.aabech.no/blog/media/1029/razorgenerator_tool.png" alt="RazorGenerator as Custom Tool for a view" /></p>
<p>As soon as you've blured the &quot;Custom Tool&quot; field, a .cs file will be generated beneath the view. Upon inspection it yields a class in the ASP namespace making a whole lot of Write* statements. This is what clutters up your ASP.NET Temporary files all the time. And the nice part: it can be instantiated. </p>
<p>Here's the initial markup from Event.cshtml:</p>
<pre><code>@model Example.WebSite.Models.Event
&lt;div&gt;
&lt;a href=&quot;@Model.Url&quot;&gt;
&lt;label&gt;
@Model.Name
&lt;/label&gt;
&lt;span&gt;
@Model.Time.ToString(&quot;f&quot;)
&lt;/span&gt;
&lt;/a&gt;
&lt;/div&gt;
</code></pre>
<p>Over in our unit test, we can now start adding some actual rendering of HTML:</p>
<pre><code>[Test]
[DocumentationOrder(2)]
public void It_Is_Rendered_With_A_Name_Date_And_A_Link()
{
var view = new _Views_Partials_Event_cshtml();
var result = GetConcertEvent();
Assert.AreEqual(&quot;Event&quot;, result.ViewName);
var renderedResult = view.Render((Event) result.Model);
Console.WriteLine(renderedResult);
Assert.Inconclusive(&quot;Rendering has not been implemented yet.&quot;);
}
private PartialViewResult GetConcertEvent()
{
httpMessageHandler.Register(
&quot;https://eventsite/api/123&quot;,
&quot;{\&quot;name\&quot;:\&quot;Concert of your life\&quot;, \&quot;time\&quot;:2524607999}&quot;
);
var result = eventController.Event(123).Result;
return result;
}
</code></pre>
<p>I know, the view type name ain't too pretty. But it's necessary for the view engine to find the right one based on the path given. The cool part is the <code>Render</code> statement. It's an extension method from the RazorGenerator.Tests package. It returns the final HTML as a string.</p>
<p>The <code>Console.WriteLine</code> statement yields the following in our test output now:</p>
<pre><code>&lt;div&gt;
&lt;a href=&quot;https://eventsite/123&quot;&gt;
&lt;label&gt;
Concert of your life
&lt;/label&gt;
&lt;span&gt;
fredag 31. desember 2049 23.59
&lt;/span&gt;
&lt;/a&gt;
&lt;/div&gt;
</code></pre>
<p><em>(Yes, I force my locale upon thee!)</em></p>
<p>What we've just done is to test our system almost end to end, cut off at the uttermost borders to external IO. Specifically, the third party site and the end-user's browser. </p>
<p>Granted, we could do Selenium tests here to really test it via the browser, but my rule of thumb is that RazorGenerator is the best choice unless you've got a lot of JavaScript interactivity you need to test in integration. These are subjects for another post.</p>
<p>There is a remaining issue though. We should assert the HTML we got rendered. We could store that HTML we got in a <code>const string expected</code> in our test, but it's gonna foul up the code quite a bit. We could go with so-called &quot;gold files&quot; and implement something to compare a file to the actual output. There's a magical tool for that called ApprovalTests, which I'll cover in my next post. </p>
<p>There's also the option of using HtmlAgilityPack to query the rendered view. The RazorGenerator.Tests package have built-in alternative for <code>Render</code> called <code>RenderAsHtml</code> that returns <code>HtmlDocument</code> instances for you to query. It's quite useful when your only <code>Assert.That</code> is for some specific element in a big page.</p>
<h2>Resources and a small limitation</h2>
<p>You've seen how you can use RazorGenerator to test your views. <a href="http://blog.davidebbo.com/tag/#RazorGenerator">There are several posts by David Ebbo (one of the authors of RazorGenerator) on how to use RazorGenerator. Please check them out for more details than I was able to give here.</a></p>
<p>For now it doesn't do nested <code>Html.Action</code> or <code>Html.Partial</code> calls. I've got a PR in the works, but I need to polish it for it to get in there. Some day soon. ;) If you really want to, you'll find my fork and build your own, but you'll be on your own.</p>
<p>There's also a tiny performance hit. You'll have to wait a second longer for your tests to execute, since a lot of the ASP.NET MVC framework is spun up to render views. It's still less than the magical 2 second focus cap though, so you should be able to work effectively with it.</p>
<p>I hope this piqued your interest in writing broader tests even up to the UI layers. There's even cooler tricks in store for you if you're already on .net Core, but the rest of us will have to make due until then.</p>
Mon, 09 Oct 2017 21:08:20 Z2017-10-09T21:08:20Z