Friday, November 29, 2013

Testing Static Classes

Sometimes when you're writing unit tests, you have a need to update what someone else wrote quite some time ago.  Sometimes (usually) there are very few to no unit tests on that existing code.  This creates a couple of problems for you in your unit testing, one of which is the fact that their code may not be architected to properly accommodate your testing.  A good example of this is when someone in the past has written a static "helper" class that is used in many places.  Now you have to use that static class and your testing will depend on the values that may or may not exist.  It's messy.  Fortunately, we have a way to solve this problem using the .NET testing framework known as Shims.

I'm going to do everything else in here with commented code instead of text.  It's just easier.

public static Dictionary<string, UrlTarget> _urlTargetLookup = new Dictionary<string, UrlTarget>();

public static string BuildUrl(string destination, string displayText, string target)
{
// check whether the lookup dictionary is null or empty
       if (_urlTargetLookup == null || !_urlTargetLookup.Any())
       {
       // if it is null or empty, populate it from the database
       // this is where our unit testing problem comes into play
       // we don't want to rely on the database results for our tests to pass
       // we're assuming that the process of getting the values from the
       // database is not conducive to mocking (there are real cases
       // where this happens)
       _urlTargetLookup = GetValuesFromDatabase();
       }

// lookup the target in the dictionary and get the enum value
       var targetString = _urlTargetLookup[target].ToString();

       // build the url
       var urlBuilder = new StringBuilder();

       urlBuilder.Append(");
       urlBuilder.Append(destination);
       urlBuilder.Append("\" target=\"");
       urlBuilder.Append(targetString);
       urlBuilder.Append("\">");
       urlBuilder.Append(displayText);
       urlBuilder.Append("
");

       // return the url
       return urlBuilder.ToString();
}


public List<Endpoint> GetEndpoints()
{
var endpoints = new List<Endpoint>
       {
              new Endpoint
              {
                     Name = "Google",
                     Url = UrlHelper.BuildUrl("http://www.google.com", "Google", "parent")
},
              new Endpoint
              {
                     Name = "Yahoo!",
                     Url = UrlHelper.BuildUrl("http://www.yahoo.com", "Yahoo!", "self")
},
              new Endpoint
              {
                     Name = "Bing",
                     Url = UrlHelper.BuildUrl("http://www.bing.com", "A Better Search Engine", "Blank")
}
};

       return endpoints;
}


[TestMethod]
public void GetEndpointsShouldReturnThreeValidUrls()
{
// arrange
       var resources = new Resources();

       // create the ShimsContext in order to use Shims later
       using (ShimsContext.Create())
       {
// UrlHelper is a static class that contains a public static field we need to set in order to mimic a dependency injection
              // create an "instance" of this static class and use this new instance for testing
              var staticType = typeof (UrlHelper);
              ConstructorInfo ci = staticType.TypeInitializer;
              var parameters = new object[0];
              ci.Invoke(null, parameters);

              // create what amounts to a mocked Dictionary object
              var endpointMapping = new Dictionary<string, UrlTarget>
              {
                     {"_parent", UrlTarget._parent},
                     {"parent", UrlTarget._parent},
                     {"_self", UrlTarget._self},
                     {"self", UrlTarget._self},
                     {"_blank", UrlTarget._blank},
                     {"Blank", UrlTarget._blank},
                     {"blank", UrlTarget._blank},
                     {"_top", UrlTarget._top},
                     {"top", UrlTarget._top}
};

// use reflection to set the public static field in our instance of the static class so we can be certain what it will contain when we test
              var dictionaryField = staticType.GetField("_urlTargetLookup");
              dictionaryField.SetValue(staticType, endpointMapping);

              // act
              var resourcesResults = resources.GetEndpoints();

// assert
              Assert.AreEqual(3, resourcesResults.Count);
              Assert.AreEqual("Google", resourcesResults[0].Url);
              Assert.AreEqual("Yahoo!", resourcesResults[1].Url);
              Assert.AreEqual("A Better Search Engine", resourcesResults[2].Url);
}
}


So there you have it.  You can test a static class without relying on information from the database.  One important item to note is that when I left my initialization of _urlTargetLookup as null, the test failed on the staticType.TypeInitializer line because the TypeInitializer did not exist.  As long as the _urlTargetLookup is initialized to be a new instance of a Dictionary, everything works as expected.

Sunday, November 24, 2013

Sometimes You Gotta Fake It

In .NET 4.0 Microsoft gave us a couple of new testing tools called Shims and Fakes.  I'm not going to profess to be an expert on those topics, nor on unit testing in general.  However, I have found there to be a dearth of information available to actually utilize these new tools to do unit testing.  I've written up a nice little blurb on how to do it and I'm going to post it here for posterity.

First we must create a ShimsContext within which we can run the tests.  ShimsContext implements IDisposable so we can do this by utilizing the using statement:

// create the ShimsContext in order to use Shims later
using (ShimsContext.Create())
{
}


Within the ShimsContext we can use Shims and Fakes to specify the exact data we want to receive when we use static methods.  The first method here specifies that when DateTime.Now is called by the code under test, it should be detoured to use “11/15/2013 9:18:13”:
// create the ShimsContext in order to use Shims later
using (ShimsContext.Create())
{
// create the Shim for DateTime.Now in order to always have a specific value when DateTime.Now is called
       System.Fakes.ShimDateTime.NowGet = () => new DateTime(2013, 11, 15, 9, 18, 13);
}

The next thing we do is create a Fake for Session.  This way we can specify an exact value for each key requested from Session.  Since we can specify a value for each key, we have full control over the session and which values will be returned, including potentially returning null so we can perform negative testing.  Here we want to specify that "12345" should be returned when the code requests "UserID" from the session and "987654" when "LoginKey" is requested:


using (ShimsContext.Create())
{
<…snip…>

// create the Fake for Session
var session = new System.Web.SessionState.Fakes.ShimHttpSessionState
{
ItemGetString = key =>
{
// specify each key that will be requested by the code under test
switch (key)
{
case "UserID":
return "123456";
  case "LoginKey":
return "987654";
default:
return null;
}
}
};
}


Now that we’ve created the Session Fake we need to create the Context Fake.  In this case I want to specify that when HttpContext.Items is called by the code under test, an empty Dictionary<string, object>() is returned:

// create the ShimsContext in order to use Shims later
using (ShimsContext.Create())
{
<…snip…>

// create the Shim for HttpContext
var context = new System.Web.Fakes.ShimHttpContext
{
ItemsGet = () => new Dictionary<string, object>()
};
}


Once the Fakes are both created, we must tell the Shims to use those objects instead of the standard objects.  These two lines specify that when HttpContext.Current is referenced we should instead substitute the Fake context we created earlier and when HttpContext.Current.Session is referenced we should instead substitute the Fake session we created earlier:

// create the ShimsContext in order to use Shims later
using (ShimsContext.Create())
{
<…snip…>

// specify that when the current context is requested we return the shimmed context we created
System.Web.Fakes.ShimHttpContext.CurrentGet = () => context;
// specify that when the current session is requested we return the shimmed session we created
System.Web.Fakes.ShimHttpContext.AllInstances.SessionGet = o => session;
}


That's pretty much it for now.  Shims and Fakes are incredibly useful, especially when you need to test a method that uses values from Session to perform differently.  I'll post again soon (hopefully) on how to instantiate a static class for testing purposes.

Tuesday, November 12, 2013

Nullify the Whitespace

Way back in the old days of .NET 1.1 if you wanted to check whether a string was empty or null you had to perform two explicit checks:

if (input == null || input == "")

Then in .NET 2.0 Microsoft gave us the IsNullOrEmpty extension of the System.String class, which combined the two calls and made your life that much easier.

if (string.IsNullOrEmpty(input))

But what to do if you also needed to check if the string starts with an empty character?  What about the dreaded whitespace "character"?  You had to implement your own solution that checked each character in the string to see if it qualified as a whitespace character (space, tab character, linefeed character, etc.).  This isn't exactly hard, but it always left a bad taste in my mouth.  I mean, how was I supposed to know what characters to look for?  What if they changed?  Were was I supposed to put this method?

In .NET 4.0, Microsoft gave us a solution: IsNullOrWhiteSpace.  This new method checks whether the string is empty (length of 0), null, or contains only whitespace characters (more on this later).  When I looked up this new feature originally I made a mental note along the lines of "performs IsNullOrEmpty, then checks if string is blank" and went on my way, using IsNullOrWhiteSpace wherever I had previously used IsNullOrEmpty.  Of course that made sense.  IsNullOrWhiteSpace must be better because it's newer, right?

The answer is yes and no.  The obvious point that I missed was these methods check for different things.  When you only care whether the string has a value, regardless of the contents of the string then you can safely use IsNullOrEmpty.  If you absolutely have to know whether the string contains nothing but whitespace then you'll want to use IsNullOrWhiteSpace.  You're probably asking yourself why you read this far to read something you already knew, and the answer to that is because I have performance metrics to show you!

Both IsNullOrEmpty and IsNullOrWhiteSpace are string extension methods so their code is pretty straightforward.  I got to wondering how each was implemented and found that they're pretty much what you'd expect:

public static bool IsNullOrEmpty(string value)
{
    if (value != null)
        return value.Length == 0;
    else
        return true;
}

public static bool IsNullOrWhiteSpace(string value)
{
    if (value == null)
        return true;
    for (int index = 0; index < value.Length; ++index)
    {
        if (!char.IsWhiteSpace(value[index]))
            return false;
    }
    return true;
}

public static bool IsWhiteSpace(char c)
{
    if (char.IsLatin1(c))
        return char.IsWhiteSpaceLatin1(c);
    else
        return CharUnicodeInfo.IsWhiteSpace(c);
}

private static bool IsWhiteSpaceLatin1(char c)
{
    return (int) c == 32 || (int) c >= 9 && (int) c <= 13 || ((int) c == 160 || (int) c == 133);
}

public static bool IsWhiteSpace(char c)
{ 
    if (IsLatin1(c))
    {
        return (IsWhiteSpaceLatin1(c)); 
    }
 
    return CharUnicodeInfo.IsWhiteSpace(c);
}

IsNullOrEmpty is about as simple as it gets.  It essentially just encapsulates what we were doing on our own before.  Now it's an extension method that's part of the framework.

IsNullOrWhiteSpace is slightly more complex, but still pretty easy to understand.  If the argument is null, return true.  If not (there's some value in it), then iterate through each character in the string and check whether that character is a whitespace character.  If it is, return false.  If it isn't, keep going.  Since the for loop starts at the 0 index and counts up, the method will exit as soon as a non-whitespace character is encountered.  This is what got me thinking of performance.

At first glance, this looks like it could end up being a monster.  Fortunately, that's only true if your input starts with a bunch of whitespace characters.  So I did what any diligent developer would do.  I coded it and ran a test:
var stopwatch = new Stopwatch();
 
var shortStringToCheck = new string('a', 100);
var longStringToCheck = new string('a', 100000);
var shortWhitespaceString = new string(' ', 100) + 'a';
var longWhitespaceString = new string(' ', 100000) + 'a';

IsNullOrEmpty test code:
   1:  stopwatch.Start();
   2:   
   3:  for (var i = 1000000000; --i >= 0;)
   4:  {
   5:      var isEmpty = string.IsNullOrEmpty("");
   6:  }
   7:   
   8:  stopwatch.Stop();
   9:  Console.WriteLine("1 billion iterations of Null/empty string: " + stopwatch.ElapsedMilliseconds);
  10:   
  11:  stopwatch.Reset();
  12:  stopwatch.Start();
  13:   
  14:  for (var i = 1000000000; --i >= 0; )
  15:  {
  16:      var isEmpty = string.IsNullOrEmpty(shortStringToCheck);
  17:  }
  18:   
  19:  stopwatch.Stop();
  20:  Console.WriteLine("1 billion iterations of Null/100 character string: " + stopwatch.ElapsedMilliseconds);
  21:   
  22:  stopwatch.Reset();
  23:  stopwatch.Start();
  24:   
  25:  for (var i = 1000000000; --i >= 0; )
  26:  {
  27:      var isEmpty = string.IsNullOrEmpty(longStringToCheck);
  28:  }
  29:   
  30:  stopwatch.Stop();
  31:  Console.WriteLine("1 billion iterations of Null/100,000 character string: " + stopwatch.ElapsedMilliseconds);

IsNullOrWhiteSpace test code:
   1:  stopwatch.Start();
   2:   
   3:  for (var i = 1000000000; --i >= 0;)
   4:  {
   5:      var isEmpty = string.IsNullOrWhiteSpace("");
   6:  }
   7:   
   8:  stopwatch.Stop();
   9:  Console.WriteLine("1 billion iterations of Whitespace/empty string: " + stopwatch.ElapsedMilliseconds);
  10:   
  11:  stopwatch.Reset();
  12:  stopwatch.Start();
  13:   
  14:  for (var i = 1000000000; --i >= 0;)
  15:  {
  16:      var isEmpty = string.IsNullOrWhiteSpace(shortStringToCheck);
  17:  }
  18:   
  19:  stopwatch.Stop();
  20:  Console.WriteLine("1 billion iterations of Whitespace/100 character string: " +
  21:                      stopwatch.ElapsedMilliseconds);
  22:   
  23:  stopwatch.Reset();
  24:  stopwatch.Start();
  25:   
  26:  for (var i = 1000000000; --i >= 0;)
  27:  {
  28:      var isEmpty = string.IsNullOrWhiteSpace(longStringToCheck);
  29:  }
  30:   
  31:  stopwatch.Stop();
  32:  Console.WriteLine("1 billion iterations of Whitespace/100,000 character string: " +
  33:                      stopwatch.ElapsedMilliseconds);
  34:   
  35:  stopwatch.Reset();
  36:  stopwatch.Start();
  37:   
  38:  for (var i = 1000000; --i >= 0;)
  39:  {
  40:      var isEmpty = string.IsNullOrWhiteSpace(shortWhitespaceString);
  41:  }
  42:   
  43:  stopwatch.Stop();
  44:  Console.WriteLine("1 million iterations of Whitespace/100 character whitespace string: " +
  45:                      stopwatch.ElapsedMilliseconds);
  46:   
  47:  stopwatch.Reset();
  48:  stopwatch.Start();
  49:   
  50:  for (var i = 1000000; --i >= 0;)
  51:  {
  52:      var isEmpty = string.IsNullOrWhiteSpace(longWhitespaceString);
  53:  }
  54:   
  55:  stopwatch.Stop();
  56:  Console.WriteLine("1 million iterations of Whitespace/100,000 character whitespace string: " + stopwatch.ElapsedMilliseconds);

Results:




















As you can see from the results, there can be a performance hit for using IsNullOrWhiteSpace when IsNullOrEmpty will suffice, depending on how much leading whitespace you have.  Keep in mind this test performed a million iterations of string.IsNullOrWhiteSpace on a string that contained 100,000 whitespace characters followed by the letter "a" and that still only took 5.7148 minutes.  That means that on average we were able to check a 100,001 character string in 3.42875 milliseconds.

In the end, it's all about using the right method for the job.