Quick Integration Tests Using JSON

Posted August 14, 2014

A few times recently I’ve picked up legacy code, with no unit tests and long complex methods and had to tweak it. In an ideal world you’d deconstruct the logic and break it down into a series of small testable steps but when time is short that’s not always an option. To avoid any “seat of the pants” hacking and the associated manual testing I sometimes find it useful to write some quick high-level tests that assess all the logic together, save me some time manually testing and provide a little bit of a safety net for future adventurers.

Checking an expected output given a specific input is easy for simple types or small data structures but it quickly turns into lots of tests or stacks of asserts if you have a large object as the result.

A simple method I have used recently to quickly compare two C# objects to ensure their properties match is to serialize the objects and compare the serialized strings to each other. Using Json.Net and NUnit you can rapidly put together a dirty test that gives you some assurance that what you are doing is working as you expect e.g.

public void AssertAreEqualByJson(object expected, object actual)
{
    var expectedJson = JsonConvert.SerializeObject(expected);
    var actualJson = JsonConvert.SerializeObject(actual);
    Assert.AreEqual(expectedJson, actualJson);
}

I’m not advocating this as a replacement for proper testing and if the test fails it can be a bit awkward to work out what the problem is (especially on large objects) but as an alternative to no tests at all it has saved me plenty of time.

tdd c# json

Cruise Control .Net Self Updating Config

Posted January 19, 2013

I’m a massive advocate of continuous integration (CI). I set up a build server for my team a few years ago and it really changed the way we worked for the better. Cruise Control .Net was the first CI software I used and despite flirting with the likes of TeamCity, FAKE and even TFS I always end up returning to Cruise Control because at the moment it does just enough for what I need and is easy to extend with plugins or Powershell when my requirements are a bit more complex.

When you first set up a build server the config is normally pretty basic but as you and your colleagues get used to it you start to realise quite what it can do for you. My current team have our CI server: pulling source code, grabbing Nuget packages, building, testing, minifying, zipping, deploying, running SQL updates, flashing our office traffic lights and updating our HipChat room every time we commit code. As you can imagine the config for this is now fairly big. A few times in the last year I’ve needed to roll back config changes and struggled so I eventually ended up shoving the config in source control. This is great but pushing the latest version into source control and then copying it onto the server seemed weird so I started to investigate whether Cruise Control could update itself.

Fortunately on Thoughtwork’s CCNet pages there is an article on just that. I quickly modified our config and ran it to try it. It works great but unfortunately if you push bad config to your source control it will trash your CCNet setup and worse, if CCNet is running you might not even find out about this till next time it restarts.

I wanted a more robust mechanism for updating the config, one that validated my config instead of blindly overwriting the master one. Fortunately CCNet ships with CCValidator.exe which is built for just this purpose.

I found that by using an exec task with a specific successExitCodes section I could create a build that failed if the config was invalid. The important task is:

<exec>
	<executable>$(CCNetValidatorPath)</executable>
	<description>Validate Config File</description>
	<baseDirectory>C:\</baseDirectory>
	<buildArgs>c:\CI\CruiseControl\ccnet.config --nogui --logfile=c:\CI\Logs\ConfigValidation.log</buildArgs>
	<buildTimeoutSeconds>30</buildTimeoutSeconds>
	<successExitCodes>0</successExitCodes>
</exec>

Note that I specify a log file. This is useful for tracking what the problem in the config actually is. You can merge it into your build output using the File publisher:

<publishers>
	<merge>
		<files>
		  <file>c:\CI\Logs\ConfigValidation.log</file>
		</files>
	</merge>
	<xmllogger/>
</publishers>

Now I know my config is under source control and I don’t even have to log onto our build server to update it.

Full config file can be downloaded from: https://bitbucket.org/colethecoder/cruise-control-auto-update-demo

continuous-integration

Simplifying Documentation In MVC With Markdown

Posted September 17, 2012

Recently I’ve been building an API for work with the new ASP.Net Web API features and needed to document the functionality for 3rd Party users. I defaulted to cranking open Word and started typing, but it felt clunky. As soon as I started to create a table to track version history I started to foresee the confusion often caused in keeping the documentation in sync with the version of the API. Add to that the API is likely to be used on multiple customer sites which may not all be on the same version of the software and there is a recipe for issues in the future.

I decided instead to opt for web based documentation built into the API to ease the potential for syncing issues. I previously posted about my new-found love of Markdown for simplifying publishing for this blog and whilst there are loads of wiki packages out there I opted for a simple Markdown based solution. Fortunately there’s already a Nuget package available to aid with this: Kiwi.Markdown.

To include in a Web API project (I’ve assumed the Razor view engine) you can start by using the Package Manager console:

PM> Install-Package Kiwi.Markdown

to keep it nicely formatted I also threw in Twitter Bootstrap:

PM> Install-Package Twitter.Bootstrap

The Kiwi.Markdown package creates a new view for you for formatting the Markdown.

Views\Wiki\Doc.cshtml

By default this file will be picking up its layout from:

Views\Shared\_Layout.cshtml

To incorporate Bootstrap into your Markdown pages, change _Layout.cshtml to:

<!DOCTYPE html>
<html>
	<head>
	    <meta charset="utf-8" />
	    <meta name="viewport" content="width=device-width" />
	    <title>@ViewBag.Title</title>
	    <link href="@Url.Content("~/Content/bootstrap.min.css")" rel="stylesheet" />
	    <style type="text/css">
	      body {
	        padding-top: 60px;
	        padding-bottom: 40px;
	      }
	    </style>
	    <link href="@Url.Content("~/Content/bootstrap.responsive-min.css")" rel="stylesheet" />
	</head>
    <body>
        <div class="navbar navbar-fixed-top">
            <div class="navbar-inner">
                <div class="container">
                    <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </a>
                    <a class="brand" href="#">DOCUMENTATION NAME HERE</a>
                    <div class="nav-collapse">
                        <ul class="nav">
                            <li class="active"><a href="#">Home</a></li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
        <div class="container">
            @RenderBody()
        </div>
            @Scripts.Render("~/bundles/jquery")
            @RenderSection("scripts", required: false)
    </body>
</html>

and your Doc.cshtml to:

@using Kiwi.Markdown
@model Document

@{
    ViewBag.Title = @Model.Title;
}

<div class="span12">
    <h1>@Model.Title</h1>

    @Html.Raw(Model.Content)
</div>

Now adding md files to:

App_Data\MarkdownFiles\

will result in nice neatly formatted good looking documentation.

markdown mvc twitter-bootstrap writing