Skip to content
Jun 19 13

Typescript 0.9

by Alex Peck

Typescript, now with generics.

Jun 1 13

Mock free testing

by Alex Peck

Jan 9 13

The surprising truth about what motivates us

by Alex Peck

Dan Pink‘s talk at the RSA.

Oct 30 12

Windows 8 administrative shares

by Alex Peck

The default Windows 8 (and 7 for that matter) configuration rejects administrator credentials for administrative shares.

To enable administrative shares add this registry key (create a .reg file with this content and merge into the registry):

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System]
"LocalAccountTokenFilterPolicy"=dword:00000001

May 22 12

Fluent Test Data Builders

by Alex Peck

Sometimes the setup code required for creating unit test dependencies can grow to the point where it distracts from the intent of the test. Instead of repeating long winded constructor calls over and over, or creating hard to reuse helper methods on individual test classes, we can use a builder class to create the test dependencies. If we give our builder a fluent interface, the tests can be both compact and readable.

Let’s say we have a Person class like this:

public class Person
{
   private readonly string firstName;
   private readonly string lastName;
   private readonly DateTime dateOfBirth;
   private readonly int shoeSize;
 
   public Person(
      string firstName, 
      string lastName, 
      DateTime dateOfBirth, 
      int shoeSize)
   {
      this.firstName = firstName;
      this.lastName = lastName;
      this.dateOfBirth = dateOfBirth;
      this.shoeSize = shoeSize;
   }
 
   public string FirstName { get { return this.firstName; } }
   public string LastName { get { return this.lastName; } }
   public int ShoeSize { get { return this.shoeSize; } }
 
   public int Age()
   {
      DateTime today = DateTime.Today;
      int age = today.Year - this.dateOfBirth.Year;
      return (this.dateOfBirth > today.AddYears(-age)) 
         ? --age 
         : age;
   }
}

And we want to test a YoungerThan method like the one below. It doesn’t depend on any part of Person except Age.

public static IEnumerable YoungerThan(
    this IEnumerable people, 
    Person person)
{
    return people.Where(p => p.Age() < person.Age());
}

It might be a bit tedious to have to create a collection of People to test this method, because the Person constructor requires us to provide a number of arguments which are not relevant to the method under test. Enter the PersonBuilder class, which provides suitable defaults and a fluent interface for mutating the Person instance it creates.

public class PersonBuilder
{
    protected string FirstName { get; set; }
    protected string LastName { get; set; }
    protected DateTime DateOfBirth { get; set; }
    protected int ShoeSize { get; set; }
 
    public PersonBuilder()
    {
        this.FirstName = "Robin";
        this.FirstName = "Banks";
        this.DateOfBirth = new DateTime(1946, 3, 26);
        this.ShoeSize = 10;
    }
 
    public PersonBuilder WithFirstName(string firstName)
    {
        this.FirstName = firstName;
        return this;
    }
 
    public PersonBuilder WithLastName(string lastName)
    {
        this.LastName = lastName;
        return this;
    }
 
    public PersonBuilder WithAge(int age)
    {
        this.DateOfBirth = DateTime.Today.AddYears(-age);
        return this;
    }
 
    public PersonBuilder WithShoeSize(int shoeSize)
    {
        this.ShoeSize = shoeSize;
        return this;
    }
 
    public Person Build()
    {
        return new Person(
            this.FirstName, 
            this.LastName, 
            this.DateOfBirth, 
            this.ShoeSize);
    }
}

With the PersonBuilder, our test might look a little like the test method below. Notice that we are able to express all the test data in terms of the test, and we didn’t need to introduce a lot of distracting values which are not part of the test.

[TestMethod]
public void YoungerThan_WithOneYoungerPerson_ReturnsOne()
{
    Person referencePerson = new PersonBuilder()
                                .WithAge(21).Build();
 
    var people = new[] 
    { 
        referencePerson, 
        new PersonBuilder().WithAge(20).Build(), 
        new PersonBuilder().WithAge(22).Build()
    };
 
    var youngerPeople = people.YoungerThan(referencePerson);
 
    Assert.AreEqual(1, youngerPeople.Count());
}
Mar 24 12

Rusty Seatpost Removal

by Alex Peck

The unremitting neglect my commuter bike has been subjected to has taken its toll over the years. Usually I only bother to fix mechanical failures, but this spring I decided to replace the rusty seatpost. I imagined it would be a relatively straight forward procedure: pull very hard and it will come out.

Unfortunately the bonding power of rust is significantly stronger than congealed baked bean juice, and cannot be penetrated with fairy liquid. As usual, Sheldon Brown has documented a number of solutions. I attempted each of them in turn, without any success.

The last resort is to cut the seatpost free, which is what I describe below.

Step 1: Cut the top of the seatpost off

First, just cut the top part of the seatpost off with a hacksaw leaving half an inch protruding from the seat tube. This is the part of the seatpost you will later grapple with, so make sure there is enough to get hold of.

Step 2: Cut a slit into the seatpost

This sounds quite simple, but I cannot overstate how laborious it is in practice. It took me about three or four hours to cut this slit. I went through three hacksaw blades. I got several blisters.

You can see in the picture above that the top of the seatpost is slightly deformed at this point, and has a chunk missing. This is the result of repeated hammer blows and a fruitless attempt at pulling the tube out before the slit was complete. I actually tore a chunk out of the seatpost, which should give you an idea of how well rust can bond steel to steel. I recommend skipping this bit.

Step 3: Coil the seatpost up inside itself

Make sure the slit is complete before you start to coil the post, otherwise the saw blade will not sit cleanly in the groove as you continue to cut. I found I was not able to generate enough torque to separate the seatpost from the seat tube all the way to the bottom by twisting alone. So, I hammered a very small screwdriver into the gap I had opened up and lubricated it with WD40. My seat tube is around 3 times the thickness of the seatpost, so this seemed unlikely to distort the seat tube. Nevertheless, be careful if you try it.

I used a pair of slip joint pliers, which are probably not ideal. Mole grips might be better and are what is recommended by Sheldon Brown.

Step 4: Pull it out

By this point I was wondering if I would need to cut some more slits, and whether it would be cheaper to simply buy a new frame instead of ten thousand more hacksaw blades. However, once I removed the screwdriver I had wedged in the gap, it was relatively easy to twist the seatpost free.

Nov 4 11

Test is dead

by Alex Peck

This is a little theatrical for my taste, but I think there is a lot of truth in the underlying theme: you should have engineers who develop and test their code. Not seperate disciplines. Savoia and Whitaker go into this a bit more in the Q&A starting at 37 mins.

Aug 23 11

fatal error C1859

by Alex Peck

Once, a friend of mine set the welcome message on his Nokia 5110 to ‘fatal error’. This totally baffled the salesmen in Carphone Warehouse.

I was equally baffled when I returned to an old C++ project and tried to compile it in a freshly installed Visual Studio 2008 SP1. I was greeted with a series of these errors:

fatal error C1859: ‘Debug\blah.pch’ unexpected precompiled header error, simply rerunning the compiler might fix this problem

Not surprisingly, simply rerunning the compiler did not fix the problem. In fact, this is caused by address space layout randomization on Windows7/Server2008, as noted here.

The hotfix is available here: Fix for Visual C++ 2008 SP1 compiler error C1859

Jul 9 11

How to do unit test reviews

by Alex Peck

At work we have begun to push unit testing and even TDD. Consequently code reviews now include more unit tests. Often, reviewers are very focused on product code, and neglect to review tests in detail.

Letting poor quality test code slip in is a big problem. Fragile tests erode confidence in unit testing as a valuable exercise, and tests which are hard to maintain just slow you down when the inevitable changes are required.

When I review unit test code, I consider the following:

  • Unit tests must favour readability. They must be compact, have a clear relationship between cause and effect, and use descriptive and meaningful phrases (DAMP).
  • Unit tests should assert once. There must be a clear relationship between test case method name and the assertion(s). This way, it is easy to determine the purpose of the test at a glance, and it is obvious what it means if the test fails.
  • Prefer state verification to behaviour verification. If you must verify behaviour (because there is no state, or it is unreasonably difficult to test state), be very careful not to over specify expectations.
  • Unit tests must be based on the public interface of a class. Testing internals makes your tests fragile. This is related to behaviour verification, sometimes you need to verify internal interactions, but this is not the same as invoking private methods in order to test them.
  • Unit tests must not contain (or contain very little) conditional logic, such as branches or loops. Conditional logic makes code harder to read.
  • Unit tests must be easy to maintain. As far as possible, DRY by applying the following techniques: use test setup/tear down methods to execute code common to all tests; implement custom verification functions or classes; use framework features like CollectionAssert, IEqualityComparer or IComparer.

Further reading/viewing:

xUnit Test Patterns
Write Maintainable Unit Tests That Will Save You Time And Tears – Roy Osherove
How to do test reviews – Roy Osherove

Jun 24 11

Steven Sinofsky’s D9 Interview

by Alex Peck

Sinofsky seems overly defensive to me. I like the Metro UI, and I think it will work well for tablets. I’m less convinced with replacing the start menu with a Metro hub.