Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can use constructor dependency injection. Example:</p> <pre><code>public class SingletonDependedClass { private string _ProviderName; public SingletonDependedClass() : this(ConfigurationManager.ConnectionStrings["main_db"].ProviderName) { } public SingletonDependedClass(string providerName) { _ProviderName = providerName; } } </code></pre> <p>That allows you to pass connection string directly to object during testing.</p> <p>Also if you use Visual Studio Team Edition testing framework you can make constructor with parameter private and test the class through the accessor.</p> <p>Actually I solve that kind of problems with mocking. Example:</p> <p>You have a class which depends on singleton:</p> <pre><code>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; ... } } </code></pre> <p>First of all <code>SingletonDependedClass</code> needs to be refactored to take <code>Singleton</code> instance as constructor parameter:</p> <pre><code>public class SingletonDependedClass { private Singleton _SingletonInstance; public SingletonDependedClass() : this(Singleton.Insatnce) { } private SingletonDependedClass(Singleton singletonInstance) { _SingletonInstance = singletonInstance; } public void SomeMethod() { string str = _SingletonInstance.SomeProperty; } } </code></pre> <p>Test of <code>SingletonDependedClass</code> (<a href="http://code.google.com/p/moq/" rel="noreferrer">Moq mocking library</a> is used):</p> <pre><code>[TestMethod()] public void SomeMethodTest() { var singletonMock = new Mock&lt;Singleton&gt;(); singletonMock.Setup(s =&gt; s.SomeProperty).Returns("some test data"); var target = new SingletonDependedClass_Accessor(singletonMock.Object); ... } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload