Share via


Testing Against Guids

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:

 [TestMethod]
 public void VerifyCreatedGuid()
 {
     GuidClass gc = new GuidClass();
  
     Guid g = gc.DoStuff();
  
     Assert.AreNotEqual<Guid>(Guid.Empty, g);
 }

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.

Next: Testing Against The Current Time

Comments

  • Anonymous
    May 12, 2007
    PingBack from http://blogs.msdn.com/ploeh/archive/2007/05/11/TestingAgainstNonDeterminism.aspx

  • Anonymous
    May 12, 2007
    This is the third in a small series of posts about testing against non-determinism. In this installation,

  • Anonymous
    May 12, 2007
    This is the first in a small series of posts about testing against non-determinism. In this installation,

  • Anonymous
    May 13, 2007
    I feel it may also be good to check if two calls to DoStuff() will (or will not) result in different Guids.

  • Anonymous
    May 13, 2007
    Hello TAG Thank you for your comment. Yes, you are right, that would be a very reasonable test to perform as well. Since you don't need to know the actual values of the Guids to test for inequality, my main point still stands :)