简体   繁体   中英

Unit Test for Singleton Pattern?

Suppose, I am using a package p1 with classes A and B. I do not have access to the implementation of package p1.

Now, in my application I want only one instance of A at any time.

I have created a singleton class C in my application for class A.

Sample:

public Class ClassC
{
    private static readonly ClassA singletonObj = new ClassA();

    private ClassC();

    public static ClassA ClassC
    {
       get
       {
          return singletonObj;
       }
    }
}

How to unit test on class C to ensure a single instance was created for my application?

If you want class A to be singleton, then your above code is irrelevent.
You should write class A like that:

 public Class ClassA { private static Singleton instance; private Singleton() {} public static Singleton Instance { get { if (instance == null) { instance = new Singleton(); } return instance; } } //Any other function & members related to ClassA } 

In Order to test the singletone, try to create few ClassA instances in your code. Good result is when on every creation of "new instance", you get the same instance, meaning - you can have 2 instances having duffrent data - they will all be kinda pointer to same instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM