如何对使用静态类的方法进行单元测试,而该静态类又使用ConfigurationElementCollection? [英] How to unit test a method which uses a static class which in turn uses ConfigurationElementCollection?

查看:136
本文介绍了如何对使用静态类的方法进行单元测试,而该静态类又使用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;
        }
    }
}

上面对单元测试来说是全新的,该代码从app config中读取一些常量值 这是我的代码在构造函数中已分配的值.

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;
     }
 }

测试代码

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

在调试时发现,ConstantHelper类无法读取Appsettings

while debugging found Appsettings are not read by the ConstantHelper class

找到了实际上可以正常工作的解决方案,错误在app.config中完成了

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

我遇到的另一个问题是ConfigSection 对于MVC应用程序web.config,无需命名空间 type =" type " 对于单元测试app.config,需要命名空间 type ="" type ,_ namespace"

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"

推荐答案

您将不得不将ConstantHelper注入到HomeController中.您可以将其连接出来然后注入.从单元测试中传递IConstantHelper的模拟对象.

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.

更新

我为ConstantHelper类定义了一个接口,使我有机会注入和模拟依赖项.

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);
    }
}

我使用Moq模拟框架.只需使用以下命令在测试项目的Package Manager控制台中安装它即可:

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

安装包最低订购量

Install-Package Moq

希望这会有所帮助.

这篇关于如何对使用静态类的方法进行单元测试,而该静态类又使用ConfigurationElementCollection?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆