Omer van Kloeten's .NET Zen

Programming is life, the rest is mere details

News

Note: This blog has moved to omervk.wordpress.com.

Omer van Kloeten's Facebook profile

Omer has been professionally developing applications over the past 8 years, both at the IDF’s IT corps and later at the Sela Technology Center, but has had the programming bug ever since he can remember himself.
As a senior developer at NuConomy, a leading web analytics and advertising startup, he leads a wide range of technologies for its flagship products.

Get Firefox


powered by Dapper 

.NET Resources

Articles :: CodeDom

Articles :: nGineer

Culture

Projects

Singleton Unit Testing - A Different Approach

Peli has posted a tip concerning singleton objects and how them being singletons interferes with the testing itself. He also added a solution to this problem. Respect to Peli for this very cool post. :)

At first, I failed to understand his method, so I debated him a bit in his comments. Eventually, I understood what he meant - he created an instance manually each time he set-up his tests.

Here's another way of doing this, if you have some instantiation code in your get accessor for Instance: Just nullify the static instance.

Here's some code that shows how:

public class Singleton
{
    private static Singleton m_Instance;

    private Singleton()
    {
        // Do Initialization Magic
    }

    public static Singleton Instance
    {
        get
        {
            if (m_Instance == null)
            {
                m_Instance = new Singleton();

                // Do Instance Getting Magic
            }

            return m_Instance;
        }
    }
}

[TestFixture]
public class MyTests
{
    [TearDown]
    public void TearDown()
    {
        System.Reflection.FieldInfo fi =
            typeof(Singleton).GetField("m_Instance",
            System.Reflection.BindingFlags.Static |
            System.Reflection.BindingFlags.NonPublic);

        Assert.IsNotNull(fi);

        fi.SetValue(null, null);
    }
}

An added bonus for this method is the ability to use the Singleton class as it was intended for it to be used. There might be some code in the get accessor that should run whenever it is accessed, regardless for the value of the private instance.

Comments

No Comments