Posted by on June 12, 2013 in C#, CSS/HTML/JavaScript, Testing

In my experience, tests that emulate real-world usage and use real-world data, find more relevant bugs, convey intent more clearly, and exercise the system under test more thoroughly than tests that do not. Consider testing a cab service to assert that a given vehicle arrives at its destination:

cabService.SendVehicleToDestination(vehicle, destination);
Assert.AreEqual(vehicle.Location, destination);

Now, it shouldn’t particularly matter what vehicle is sent, or to where it is sent, but it’s often valuable to provide objects to methods that looks like the kind of objects an actual consumer of the service would send. Enter Randomator, a tool I created to use when scaffolding test objects:

public Vehicle MakeRandomVehicle()
{
    return new Vehicle
    {
        Color = Randomator.RandomColor(),
        Year = Randomator.RandomNumber(2000, DateTime.Now.Year + 1),
        Make = _makes[Randomator.RandomNumber(_makes.Length)],
        Owner = string.Format("{0} {1}", Randomator.RandomFirstName(
                Randomator.Gender.Any), Randomator.RandomLastName())
    };
}

A sample run produces:

Vehicle

Put it all together and the test looks like:

// Arrange
CabService cabService = new CabService();
Vehicle vehicle = MakeRandomVehicle();
String destination = Randomator.RandomLocation();

// Act
cabService.SendVehicleToDestination(vehicle, destination);

// Assert
Assert.AreEqual(vehicle.Location, destination);

This is, of course, a rather contrived example. We don’t have a cab service at Ancestry.com, fun as that would be, but as a family history company, we do have a lot person, event, location, and relationship objects for which this tool proves useful. Randomator has seen extensive use, enough so that I’ve ported it from C# to JavaScript and Java and made it available to the public under the MIT license. Check it out at: https://github.com/Ancestry/Testing-Utilities

About Anders

Anders Lyman is a Software Engineer at Ancestry.com in Story Engineering. He and his team are innovators, creating tools that are often adopted and used by other teams. He enjoys reading, cooking, spending time with his beautiful wife and playing with his 9 month old daughter.


We really do appreciate your feedback, and ask that you please be respectful to other commenters and authors. Any abusive comments may be moderated.

Commenting is open until Wednesday, 26 June 2013