Unit testing with singletons

前端 未结 4 1888
萌比男神i
萌比男神i 2020-11-27 09:27

I have prepared some automatic tests with the Visual Studio Team Edition testing framework. I want one of the tests to connect to the database following the normal way it is

4条回答
  •  -上瘾入骨i
    2020-11-27 09:57

    You can use constructor dependency injection. Example:

    public class SingletonDependedClass
    {
        private string _ProviderName;
    
        public SingletonDependedClass()
            : this(ConfigurationManager.ConnectionStrings["main_db"].ProviderName)
        {
        }
    
        public SingletonDependedClass(string providerName)
        {
            _ProviderName = providerName;
        }
    }
    

    That allows you to pass connection string directly to object during testing.

    Also if you use Visual Studio Team Edition testing framework you can make constructor with parameter private and test the class through the accessor.

    Actually I solve that kind of problems with mocking. Example:

    You have a class which depends on singleton:

    public class Singleton
    {
        public virtual string SomeProperty { get; set; }
    
        private static Singleton _Instance;
        public static Singleton Insatnce
        {
            get
            {
                if (_Instance == null)
                {
                    _Instance = new Singleton();
                }
    
                return _Instance;
            }
        }
    
        protected Singleton()
        {
        }
    }
    
    public class SingletonDependedClass
    {
        public void SomeMethod()
        {
            ...
            string str = Singleton.Insatnce.SomeProperty;
            ...
        }
    }
    

    First of all SingletonDependedClass needs to be refactored to take Singleton instance as constructor parameter:

    public class SingletonDependedClass
    {    
        private Singleton _SingletonInstance;
    
        public SingletonDependedClass()
            : this(Singleton.Insatnce)
        {
        }
    
        private SingletonDependedClass(Singleton singletonInstance)
        {
            _SingletonInstance = singletonInstance;
        }
    
        public void SomeMethod()
        {
            string str = _SingletonInstance.SomeProperty;
        }
    }
    

    Test of SingletonDependedClass (Moq mocking library is used):

    [TestMethod()]
    public void SomeMethodTest()
    {
        var singletonMock = new Mock();
        singletonMock.Setup(s => s.SomeProperty).Returns("some test data");
        var target = new SingletonDependedClass_Accessor(singletonMock.Object);
        ...
    }
    

提交回复
热议问题