Krishjs
Krishjs

Reputation: 368

How to unit test a method which uses a static class which in turn uses ConfigurationElementCollection?

public class ConfigSection : ConfigurationSection
{        
    public static ConfigSection GetConfigSection()
    {
        return (ConfigSection)System.Configuration.ConfigurationManager.
           GetSection("ConfigSections");
    }

    [System.Configuration.ConfigurationProperty("ConstantsSettings")]
    public ConstantSettingCollection ConstantsSettings
    {
        get
        {
            return (ConstantSettingCollection)this["ConstantsSettings"] ??
               new ConstantSettingCollection();
        }
    }


    public class ConstantSettingCollection : ConfigurationElementCollection
    {   

        public ConstantElements this[object key]
        {
            get
            {
                return base.BaseGet(key) as ConstantElements;
            }
            set
            {
                if (base.BaseGet(key) != null)
                {
                    base.BaseRemove(key);
                }
                this.BaseAdd(this);
            }
        }

        protected override ConfigurationElement CreateNewElement()
        {
            return new ConstantElements();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((ConstantElements)element).Key;
        }
    }

    public class ConstantElements : ConfigurationElement
    {
        [ConfigurationProperty("key", IsRequired = true)]
        public string Key
        {
            get
            {
                return this["key"] as string;
            }
        }

        [ConfigurationProperty("val", IsRequired = true)]
        public string Constants
        {
            get { return this["value"] as string; }
        }          
    }        
}
    
public class ConstantHelper
{   
    public static string ConstantForLog
    {
        get
        {
            return ConfigSection.GetConfigSection().ConstantsSettings["ConstantForLog"].Constants;
        }
    }
}

Totally new to unit testing above is the code which reads some constant values from app config here is my Code in the constructor have assigned the value.

public class HomeController
{
    protected string constants;
    public HomeController()
     {
         constants = ConstantHelper.ConstantForLog;
     }
 }

Test Code

[TestClass]
public class HomeControllerTester
{
 [TestMethod]
 public void Initialize_Tester()
  {
    //Creating Instance for the HomeController
    HomeController controller = new HomeController();
  }
}

while debugging found Appsettings are not read by the ConstantHelper class

Solution

Found the solution actually it works fine mistake is done in app.config

Also another problem I faced is in ConfigSection For MVC app web.config there is no need for namespace type="type" where as for unit test app.config there is a need of namespace type="type,_namespace"

Upvotes: 2

Views: 2312

Answers (1)

SBirthare
SBirthare

Reputation: 5137

You will have to inject ConstantHelper into HomeController. You can interface it out and then inject it. From unit test pass a mock object of IConstantHelper.

UPDATE

I have defined an interface for ConstantHelper class to give me an opportunity to inject and mock the dependency.

ConstantHelper.cs

public class ConstantHelper : IConstantHelper
{
    public string ConstantForLog
    {
        get
        {
            return ConfigSection.GetConfigSection().ConstantsSettings["ConstantForLog"].Constants;
        }
    }
}

public interface IConstantHelper
{
    string ConstantForLog { get; }
}

HomeController.cs

Note I am now injecting the constant helper from outside so the unit test can mock it.

public class HomeController : Controller
{
    private readonly IConstantHelper _constantHelper;

    public HomeController(IConstantHelper constantHelper)
    {
        _constantHelper = constantHelper;
    }

    public ActionResult Index()
    {
        return View(_constantHelper.ConstantForLog);
    }
}

HomeControllerTest.cs

[TestClass]
public class HomeControllerTest
{
    [TestMethod]
    public void Index_WithDependecySetupCorrectly_ReturnTestString()
    {
        var mockHelper = new Mock<IConstantHelper>();
        const string testDataString = "TestString";
        mockHelper.Setup(z => z.ConstantForLog).Returns(testDataString);

        //Creating Instance for the HomeController
        var controller = new HomeController(mockHelper.Object);

        var result = controller.Index() as ViewResult;

        Assert.IsNotNull(result);
        Assert.AreEqual(testDataString, result.ViewName);
    }
}

I use Moq mocking framework. Just install it using following command in Package Manager Console in your test project:

Install-Package Moq

Hope this helps.

Upvotes: 4

Related Questions