I am filled with solutions

Weekly essays on testability, testing and being a tester.

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.

 

Published Monday, November 03, 2008 9:55 PM by SaintD

Comments

No Comments
Anonymous comments are disabled

About SaintD

Dustin Andrews has been testing software at Microsoft since 2001. He currently programs primary in C# and has loved it ever since he learned it had a good regex class. He came from the industry where he has been an ISP unix admin, Perl and SQL developer, dev lead, help desk technician and manager. He has also waited tables, worked many long nights as a convenience store clerk disinfected shoes in a bowling alley and done other jobs he has blocked out of his memory. He is currently in the Unlimited Potential Group as a Server Test Lead.

© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Microsoft
Page view tracker