This is the second in a small series of posts about testing against non-determinism. In this installation, I’m going to cover Guids.
Despite sharing some similarities with random numbers, Guids actually turn out to be a lot less difficult to use in unit testing. The main reason is that in contrast to a random number, you don’t really care about the specific value of a newly created Guid. While you may care about the value of predefined Guids, these are also known to the test developer at design-time, so they are generally not an issue. The thing to keep in mind here is that a Guid is only non-deterministic before it has been created (sic).
While I can think of a number of scenarios where you would want to write conditional logic based on the value of predefined Guids, I can’t think of a single scenario where you would create a new Guid and perform conditional logic on it in the same operation. Since the value doesn’t carry any information besides the value itself, branching on it if the value isn’t known at design-time is absurd. Even so, if you ever find yourself in a situation where you need to control Guid generation from a unit test, you can always use the Provider Injection pattern.
For a newly created Guid, the only thing you are probably going to care about from a unit testing perspective is whether a new Guid was actually returned. However, you don’t need to be able to override the Guid creation process to unit test that. Imagine that you have a class with the ubiquitous DoStuff method returning a Guid. Testing this method is as simple as this:
public void VerifyCreatedGuid()
GuidClass gc = new GuidClass();
Guid g = gc.DoStuff();
In contrast to other types of non-determism, Guids are really a non-issue in a testing context – mainly because a Guid carries no information.