Darrell Norton's Blog [MVP]

Sponsors

The Lounge

Wicked Cool Jobs

News

  • Darrell Norton pic

    MVP logo

    View Darrell Norton's profile on LinkedIn

    Currently Reading:

    weewar.com

Advertisement

Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
Unit testing a singleton

Jonathan de Halleux shows the simple way to test a singleton. Given this sample code:

using System;
public sealed class Singleton
{
   ...
   private Singleton() {}
   public static Singleton Instance
   {
      get { ...}
   }
}

You can test it with reflection like this:

using System.Reflection; 
[TestFixture]
public class SingletonTest
{
    private Singleton target = null;
    [SetUp]
    public void SetUp()
    {
        ConstructorInfo ci =
            typeof(Singleton).GetConstructor(
                BindingFlags.Instance |
                BindingFlags.NonPublic,
                null,
                Type.EmptyTypes,
                null
                );
         Assert.IsNotNull(ci);
         this.target = (Singleton)ci.Invoke(null);
    }
}

Posted Wed, Aug 18 2004 6:28 AM by Darrell Norton

[Advertisement]

Devlicio.us