简体   繁体   English

单例模式的单元测试?

[英]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. 假设我正在使用具有类A和B的软件包p1。我无权访问软件包p1的实现。

Now, in my application I want only one instance of A at any time. 现在,在我的应用程序中,我随时都只需要一个A实例。

I have created a singleton class C in my application for class A. 我在A类的应用程序中创建了一个Singleton类C。

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? 如何对C类进行单元测试以确保为我的应用程序创建了一个实例?

If you want class A to be singleton, then your above code is irrelevent. 如果您希望A类为单例,则上面的代码为irrelevent。
You should write class A like that: 您应该这样编写A类:

 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. 为了测试单调,请尝试在您的代码中创建几个ClassA实例。 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. 好的结果是,在每次创建“新实例”时,您都获得相同的实例,这意味着-您可以有2个实例,这些实例具有不合法的数据-它们全都是指向同一实例的指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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