Creating Guid from String for unit testing

I was sitting with a unit test where a mock needed to create a GUID. I didn’t want to manually type a long list of GUIDs so I started to think. What if I could have my GUIDs created from something that’s simpler to remember like a string. So I created the following extension method on string creating a GUID using MD5.

Unlike normal GUIDs these are not unique in the traditional sense of the word so don’t use this code for anything other than unit tests

public static class GuidExtension
public static Guid ToGuid(this string input)
var md5 = System.Security.Cryptography.MD5.Create();
var inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
var hash = md5.ComputeHash(inputBytes);
var result = new Guid(hash);
return result;
Use the extension method like this
Guid TestGuid = "TestGuid".ToGuid();

This will create the following Guid

No comments:

Post a Comment