Testing add and remove using GUID’s


When testing features of your product it is often necessary to test state changing methods.

For example, consider a method which adds an string to a hashmap. The first time you call it you will get an “OK” message but the second time you call it you should get a “That object already exists” message.

An example test might look something like:

GivenTheApplicationIsRunningAndTheObjectDoesNotExist
WhenObject1IsAdded
ThenObject1ShouldReturnOK

Now if you implement the test in a naive fashion, simply calling “addObject(‘Object1′)” then the test will pass the first time, but the second time the test will fail, as the object already exists, contravening the Given statement.

There are three options to deal with these problems:

  1. Start the test with a clean environments.
  2. Remove your objects after you add them
  3. Use GUIDs

Of the first two options, I think that the 1st is the better option. Making your tests isolated from others is a good plan. it should be somewhat trivial to reimage your database or restart your application and you will be able to run the test cleanly. However sometimes it is inconvenient to restart or initialise your application. If it requires more than a few seconds to start the application from scratch it can be very annoying to have to restart it between each test, especially when your tests start to get into the dozens.

There is a solution. Use GUIDs. A globally unique identifier is (virtually) guaranteed to be unique in time and space. This makes it ideal for testing add and removes as you can be sure that it will not be in your database before your test no matter how many times you run it. As long as you bear in mind that you should initialise the database every now and then to stop it getting too full of data, using GUIDs can be a great way to test this kind of functionality without having to constantly reinitialise your application.

Spotted a problem? Think there is a better way? Discuss it in the comments!

Related Posts with Thumbnails

There are no comments yet, add one below.

Leave a Comment