Sunday, January 23, 2011

Using NUnit to explore static field initialization

Given the following code:



class Constants
{
public static readonly Constants Instance = new Constants();
public static readonly string ApplicationName = "ig2600";
public readonly string CachedClassName;

public Constants()
{
CachedClassName = GetQualifiedClassName("Constants");
}

public static string GetQualifiedClassName(string className)
{
return string.Format("{0}::{1}", ApplicationName, className);
}
}


Which of the below tests pass?

[TestFixture]
public class TestConstants
{
[TestFixture]
public class TestConstants
{
[Test]
public void TestOne()
{
Assert.That(Constants.Instance.CachedClassName, Is.EqualTo("ig2600::Constants"));
}

[Test]
public void TestTwo()
{
Assert.That(Constants.Instance.CachedClassName, Is.EqualTo("::Constants"));
}
}
}


Not sure? Download the code with mercurial from  https://bitbucket.org/idvorkin/ig2600_blog, then fire up VS and NUnit, and look at the StaticFieldMystery project.

0 comments:

Post a Comment