<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="https://blog.aabech.no/rss/xslt"?>
<rss xmlns:a10="http://www.w3.org/2005/Atom" version="2.0">
  <channel>
    <title>Lars-Erik's blog</title>
    <link>https://blog.aabech.no/</link>
    <description>Ramblings about Umbraco, .net and JavaScript development. With a sprinkle of other stuff.</description>
    <generator>Articulate, blogging built on Umbraco</generator>
    <item>
      <guid isPermaLink="false">1139</guid>
      <link>https://blog.aabech.no/archive/environmental-approvaltests/</link>
      <category>unit testing</category>
      <title>Environmental ApprovalTests</title>
      <description>&lt;h2&gt;Background&lt;/h2&gt;
&lt;p&gt;A while ago I wrote a &lt;a href="//blog.aabech.no/archive/exploiting-approvaltests-for-clearer-tests/"&gt;post about a tool called ApprovalTests&lt;/a&gt;. I've included it in my workshop on unit testing Umbraco, and people are amazed at its usefulness. Having Visual Studio pop a diff in your face when stuff breaks is a real timesaver. However, when I ran the workshop at CodeGarden 18, I realized people were concerned that their tests would be impossible to run in CI environments and the like. Not to worry - ApprovalTests have you covered. (Pun intended)&lt;/p&gt;
&lt;h2&gt;Environmentalism&lt;/h2&gt;
&lt;p&gt;When declaring reporters with ApprovalTests, you can specify multiple reporters. That's not all. The reporters have an extensive API on them, which caters for us tailoring everything. There is one particularly interesting interface on all &amp;quot;diff-reporters&amp;quot; named &lt;code&gt;IEnvironmentAwareReporter&lt;/code&gt;.&lt;br /&gt;
The &lt;code&gt;VisualStudioReporter&lt;/code&gt; one has a nice little one-liner implementation:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public override bool IsWorkingInThisEnvironment(string forFile)
{
    return OsUtils.IsWindowsOs() &amp;amp;&amp;amp; base.IsWorkingInThisEnvironment(forFile) &amp;amp;&amp;amp; LaunchedFromVisualStudio();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The last function call there checks if the current process is a descendent of &lt;code&gt;devenv.exe&lt;/code&gt;. If it isn't, execution will just be passed to the next reporter in the chain. So there! It won't break your CI build.&lt;/p&gt;
&lt;p&gt;But what do we want in our CI build, then? Probably a regular WhateverUnit assertion. I use NUnit, so that'll be our example.&lt;/p&gt;
&lt;h2&gt;Falling back&lt;/h2&gt;
&lt;p&gt;Take this little test. I approved the result for seed 1, and we'll examine the output for an invalid result by swapping to 2:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[TestFixture]
[UseReporter(typeof(VisualStudioReporter))]
public class When_Running_In_Different_Environments
{
    [Test]
    public void Delegates_To_Most_Appropriate_Reporter()
    {
        var rnd = new Random(1);
        var items = Enumerable
            .Range(0, 10)
            .Select(x =&amp;gt; rnd.Next());
        Approvals.VerifyAll(items, &amp;quot;&amp;quot;);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Let's change the seed to 2 to fail the test:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var rnd = new Random(2);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now if we run the test with NUnit3-Console.exe, we'll get an exception saying that ApprovalTests can't find Visual Studio:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;nunit3-console.exe .\bin\debug\environmentaltests.dll

...
1) Error : EnvironmentalTests.When_Running_In_Different_Environments.Delegates_To_Most_Appropriate_Reporter
System.Exception : Couldn't find Visual Studio at
at ApprovalTests.Reporters.GenericDiffReporter.Report(String approved, String received) in C:\code\ApprovalTests.Net\ApprovalTests\Reporters\GenericDiffReporter.cs:line 142
...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It sounds worse than it is. ApprovalTests insists that it has &lt;em&gt;something&lt;/em&gt; to do. We can add a reporter to the fixture to fix it:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[TestFixture]
[UseReporter(typeof(VisualStudioReporter), typeof(NUnitReporter))]
public class When_Running_In_Different_Environments
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now when we run the test, we get a pure assertion failure:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;1) Failed : EnvironmentalTests.When_Running_In_Different_Environments.Delegates_To_Most_Appropriate_Reporter
Expected string length 165 but was 162. Strings differ at index 6.
Expected: &amp;quot;[0] = 534011718\n[1] = 237820880\n[2] = 1002897798\n[3] = 165700...&amp;quot;
But was:  &amp;quot;[0] = 1655911537\n[1] = 867932563\n[2] = 356479430\n[3] = 211537...&amp;quot;
-----------------^
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Notice it didn't even mention Visual Studio. Going back into our favorite IDE will start popping diffs again, and the NUnit one will govern the output.&lt;/p&gt;
&lt;h2&gt;Cleaning up&lt;/h2&gt;
&lt;p&gt;So should we go around declaring at least two reporters on all our fixtures, then? Luckily not. There are two more tricks that are nice to know.&lt;/p&gt;
&lt;p&gt;First, the reporter attribute is found by iterating up the inheritance hierarchy. It can be defined as high up as all your &lt;code&gt;[assembly:XAttribute]&lt;/code&gt; metadata. You can create a file in your test project root called &lt;code&gt;ApprovalsConfig.cs&lt;/code&gt; for instance. Within it, you declare your reporters on the assembly level:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;using ApprovalTests.Reporters;

[assembly:UseReporter(typeof(VisualStudioReporter), typeof(NUnitReporter))]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The second is that you might not want the NUnit assertion when you run in VS (for some reason), or maybe some other tool might be in your way. You might even want composite reporters. In any case, it also makes for a bit nicer setup if you implement the &lt;code&gt;FirstWorkingReporter&lt;/code&gt; class:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class EnvironmentReporter : FirstWorkingReporter
{
    public static readonly EnvironmentReporter INSTANCE = new EnvironmentReporter();

    public EnvironmentReporter()
        : base(
            VisualStudioReporter.INSTANCE,
            NUnitReporter.INSTANCE
        )
    {
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With it, we can change our &lt;code&gt;UseReporter&lt;/code&gt; to be:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[assembly:UseReporter(typeof(EnvironmentReporter))]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now the first reporter to confirm its environment is executed, and the rest are ignored. You might want to keep the NUnit one around, though. In that case, you can implement &lt;code&gt;MultiReporter&lt;/code&gt; in the same way - which coincidentally is the same that &lt;code&gt;UseReporterAttribute&lt;/code&gt; does.&lt;/p&gt;
&lt;p&gt;I encourage you to go have a look at &lt;a href="https://github.com/approvals/ApprovalTests.Net/tree/master/ApprovalTests/Reporters"&gt;all the built-in reporters&lt;/a&gt; and get some inspiration for even more helpful reporting.&lt;/p&gt;
&lt;p&gt;I'd rejoice for any cool usages in the discussion thread. :)&lt;/p&gt;
</description>
      <pubDate>Sun, 03 Jun 2018 21:24:46 Z</pubDate>
      <a10:updated>2018-06-03T21:24:46Z</a10:updated>
    </item>
    <item>
      <guid isPermaLink="false">1133</guid>
      <link>https://blog.aabech.no/archive/exploiting-approvaltests-for-clearer-tests/</link>
      <category>unit testing</category>
      <title>Exploiting ApprovalTests for clearer tests</title>
      <description>&lt;h2&gt;What's this for?&lt;/h2&gt;
&lt;p&gt;Ever written several asserts in one test because you have a big graph you want to verify? How 'bout files or maybe &lt;a href="/archive/testing-views-with-razorgenerator"&gt;razor views&lt;/a&gt;? Several asserts often clutter up the tests. Big strings also make the actuall calls hard to see for all that content. Putting big strings in files is a good idea to avoid that, but few people do. It adds another &amp;quot;menial&amp;quot; task when you're in the zone. But what if it was dead easy?&lt;/p&gt;
&lt;p&gt;I once maintained a Resharper extension, and their example tests had so called &amp;quot;gold&amp;quot; files that they compared to output. The squigglies was represented by special characters around terms. So they just compared the output of a text renderer to the text in a file. Great idea. One limitation though: with a regular Assert.Equals you just see the segment around the first mismatch. Guess what, there's a tool that's been around for at least 10 years that solves all those issues, and more.&lt;/p&gt;
&lt;h2&gt;Approval tests, eh?&lt;/h2&gt;
&lt;p&gt;Sounds a bit like acceptance tests, right? Don't be fooled, it's purpose is to serve all the way down to the &amp;quot;unit test layer&amp;quot; of your tests. I've found it to be a huge timesaver, as well as making my tests so much more clear.&lt;/p&gt;
&lt;p&gt;I know you're thinking &amp;quot;Shut up and give me an example, then!&amp;quot;, so let's have a look. I've got this unit test from my post about &lt;a href="/archive/testing-views-with-razorgenerator"&gt;testing razor views&lt;/a&gt; that I never really asserted anything in. I just output the result to console and assert inconclusive. Here it is for reference:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[TestFixture]
public class When_Displaying_An_Event
{
    [Test]
    public void It_Is_Rendered_With_A_Name_Date_And_A_Link()
    {
        var view = new _Views_Partials_Event_cshtml();
        var actionResult = GetConcertEvent();

        Assert.AreEqual(&amp;quot;Event&amp;quot;, actionResult.ViewName);

        var renderedResult = view.Render((Event) actionResult.Model);

        Console.WriteLine(renderedResult);
        Assert.Inconclusive(&amp;quot;Way too big to assert here.&amp;quot;);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It outputs the following HTML:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;div&amp;gt;
    &amp;lt;a href=&amp;quot;https://eventsite/123&amp;quot;&amp;gt;
        &amp;lt;label&amp;gt;
            Concert of your life
        &amp;lt;/label&amp;gt;
        &amp;lt;span&amp;gt;
            fredag 31. desember 2049 23.59
        &amp;lt;/span&amp;gt;
    &amp;lt;/a&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Let's see it&lt;/h2&gt;
&lt;p&gt;Now let's assert this with ApprovalTests. To use it, you just &lt;code&gt;install-package ApprovalTests&lt;/code&gt; with your trusty package manager console. Make sure to install it in your test project. ;)&lt;/p&gt;
&lt;p&gt;Now instead of &lt;code&gt;Assert&lt;/code&gt;, we ask ApprovalTests to &lt;code&gt;Verify&lt;/code&gt; our data instead. It even has a special overload for this concrete case: &lt;code&gt;Approvals.VerifyHtml&lt;/code&gt;. So we rewrite the test as such:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[Test]
public void It_Is_Rendered_With_A_Name_Date_And_A_Link()
{
    var view = new _Views_Partials_Event_cshtml();
    var actionResult = GetConcertEvent();

    Assert.AreEqual(&amp;quot;Event&amp;quot;, actionResult.ViewName);

    var renderedResult = view.Render((Event) actionResult.Model);

    Approvals.VerifyHtml(renderedResult);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now when we run our test, we get this nice little welcoming message from ApprovalTests:&lt;/p&gt;
&lt;p&gt;&lt;img src="https://blog.aabech.no/media/1033/welcome-to-approvaltests.png" alt="Exception: Welcome to ApprovalTests" /&gt;&lt;/p&gt;
&lt;p&gt;It tells us we're missing a vital part: A reporter. It's possible to use &lt;code&gt;DiffReporter&lt;/code&gt; to launch your favorite configured difftool. But if you're in Visual Studio, there's a special treat: &lt;code&gt;VisualStudioReporter&lt;/code&gt;. Let's add that to our fixture and see what happens:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[UseReporter(typeof(VisualStudioReporter))]
[TestFixture]
public class When_Displaying_An_Event
{
    [Test]
    public void It_Is_Rendered_With_A_Name_Date_And_A_Link()
    {
        // ...
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And we run it:&lt;/p&gt;
&lt;p&gt;&lt;img src="https://blog.aabech.no/media/1032/first-result.png" alt="ApprovalTests first result have empty approved" /&gt;&lt;/p&gt;
&lt;p&gt;What hits you is probably the big failure statement there, but look again - up at the top there.
We've got a diff opened, the result on the left hand and a big green field on the right side.&lt;br /&gt;
What just happened is that ApprovalTests took our result, stored it in a received file, and at the same time wrote an empty &amp;quot;approved&amp;quot; file. It then proceeded to compare, and finally pop a diff of those two files.&lt;br /&gt;
Isn't that just beautiful? Everything that makes your test fail in one clear diagram.&lt;/p&gt;
&lt;p&gt;The &amp;quot;procedure to follow&amp;quot; here, is to &amp;quot;approve&amp;quot; results when you're happy. To do that, you just copy and paste. Let's do that now:&lt;/p&gt;
&lt;p&gt;&lt;img src="https://blog.aabech.no/media/1030/first-approved.png" alt="First approved with invalid indenting" /&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;If you've got ReSharper, it's probably gonna try to format everything nicely when you paste. To have it in the original, ugly indentation state, press Ctrl+Z (undo) once after pasting.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Regarding the indentation that's off. It seems to be a bug with HTML in the current version of ApprovalTests, so stupid me for choosing this example. I'll update the post if it gets fixed.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;We can now run our test again, and it's gonna pass. When it passes, it doesn't bother to open the diff.&lt;/p&gt;
&lt;p&gt;&lt;img src="https://blog.aabech.no/media/1031/first-passing.png" alt="It passes with an approved file" /&gt;&lt;/p&gt;
&lt;p&gt;This means we're just gonna get diffs for whatever is currently failing. Even if we run our entire suite of tests. Now there's a couple of housekeeping things to keep in mind:&lt;/p&gt;
&lt;h2&gt;Commit approvals only&lt;/h2&gt;
&lt;p&gt;If you were paying attention, you noticed we got two files adjacent to our test source file. One is named [TestFixtureName].[TestMethodName].received.html and one is named [TestFixtureName].[TestMethodName].approved.html. If you ran a test that passed, you'll actually just have your approved file. &lt;strong&gt;You want those approved files in source control!&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The received files though, might end up not being cleaned up for one or the other reason. Hopefully just that you didn't bother to commit a fully passing build. I'm sure you didn't do that to the master branch, though. In any case, make sure to &lt;em&gt;ignore&lt;/em&gt; your received files. This pattern in .gitignore generally does the trick:&lt;/p&gt;
&lt;p&gt;&lt;code&gt;*.received.*&lt;/code&gt; &lt;/p&gt;
&lt;h2&gt;That's just the tip of the iceberg&lt;/h2&gt;
&lt;p&gt;We've seen the &lt;code&gt;VerifyHtml&lt;/code&gt; bit. One of my personal favorites is it's sibling &lt;code&gt;VerifyJson&lt;/code&gt;. I keep an extension on &lt;code&gt;object&lt;/code&gt; in my tests, called &lt;code&gt;.ToJson()&lt;/code&gt;. With it, I can just go:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Approvals.VerifyJson(myBigGraph.ToJson());
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The diff is done with prettified JSON, so it's super simple to find the property / area that has changed or doesn't work. Knowing the area of the graph should also make it easier to find the usage that is wrong.&lt;/p&gt;
&lt;p&gt;There's a vanilla &lt;code&gt;Verify&lt;/code&gt; method too, and it saves plain text files. It's useful in cases where you have nice &lt;code&gt;ToString()&lt;/code&gt; implementations. Let's try with a &amp;quot;person&amp;quot;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }

    public override string ToString()
    {
        return $&amp;quot;{FirstName} {LastName} ({Age})&amp;quot;;
    }
}

[Test]
public void Comparing_Objects()
{
    var person = new Person
    {
        FirstName = &amp;quot;Lars-Erik&amp;quot;,
        LastName = &amp;quot;Aabech&amp;quot;,
        Age = 19
    };

    Approvals.Verify(person);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It produces the following .received file:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Lars-Erik Aabech (19)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It can be approved like that.&lt;br /&gt;
We can also do lists with &amp;quot;big brother&amp;quot; &lt;code&gt;VerifyAll&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[Test]
public void Comparing_Lists()
{
    var list = new List&amp;lt;Person&amp;gt;
    {
        new Person {FirstName = &amp;quot;Lars-Erik&amp;quot;, LastName = &amp;quot;Aabech&amp;quot;},
        new Person {FirstName = &amp;quot;Dear&amp;quot;, LastName = &amp;quot;Reader&amp;quot;}
    };

    Approvals.VerifyAll(list, &amp;quot;&amp;quot;);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Which, unsurprisingly outputs:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[0] = Lars-Erik Aabech
[1] = Dear Reader
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now how bout that?&lt;br /&gt;
I don't know how quickly you got hooked, but I certainly find it sneaking into more and more of my tests.&lt;/p&gt;
&lt;p&gt;It can even do images, but I'll let &lt;a href="http://jamessouth.me/"&gt;James&lt;/a&gt; blog about that one.&lt;/p&gt;
&lt;p&gt;So what are you lingering around here for? Run over to nuget and get your copy, or lurk around some more at the &lt;a href="http://approvaltests.sourceforge.net/"&gt;ApprovalTests&lt;/a&gt; project site. There's great examples, even though they might not be in your favorite language.&lt;/p&gt;
&lt;p&gt;Happy approving! :)&lt;/p&gt;
</description>
      <pubDate>Mon, 23 Oct 2017 20:14:08 Z</pubDate>
      <a10:updated>2017-10-23T20:14:08Z</a10:updated>
    </item>
  </channel>
</rss>