The right and wrong way to create unique data for tests.

I have noticed some code in various places that creates some conditions for mysterious test failures. You know the kind; “It works on my machine but will never seem to run in the lab.”

In our tests its sometimes desirable to have a unique identifier. There are a lot of possible ways to create this data, but only one is sure fire. Use GUIDS.

Let’s say we are creating ID strings for whatever reason.

 

The right way: Use GUIDs.

string uniqueString = Guid.NewGuid().ToString("N"); //N removes punctuation to keep the length to 32.

Guids are designed to be unique. Don’t worry about collisions. Don’t worry about running out. If you can afford the 32 characters, use a GUID.

Hint: Guids are hexadecimal numbers. If you need to “compress” one you can get a 32 digit GUID into 13 digits by converting it to base64.

 

The appealing wrong way: Combine the time with a random number.

            Random random = new Random();

         string uniqueString = DateTime.Now.ToString() + random.Next(1000); //Random doesn't mean "no duplicates!". You are prone to the Birthday Paradox.

You can fiddle with the time output to get this down to about 20 characters. If your tests run in 1/100th of a second or concurrent runs you will run into problems due to the birthday paradox.

 

The really wrong ways: Time only, Random Only.

        string uniqeName = "MyTests" + DateTime.Now.ToString();//If you run this too fast or concurrently you will get duplicates. Easy to do!

Or

        private static Random random = new Random();

        String uniqueName = random.Next().ToString(CultureInfo.InvariantCulture); //Random doesn't mean "no duplicates!". You are prone to the Birthday Paradox.