如何使用 moq 模拟 ConfigurationManager.AppSettings [英] How to mock ConfigurationManager.AppSettings with moq

查看:27
本文介绍了如何使用 moq 模拟 ConfigurationManager.AppSettings的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被困在我不知道如何模拟的代码点上:

I am stuck at this point of code that I do not know how to mock:

ConfigurationManager.AppSettings["User"];

我必须模拟 ConfigurationManager,但我不知道,我正在使用 起订量.

I have to mock the ConfigurationManager, but I don't have a clue, I am using Moq.

有人可以给我小费吗?谢谢!

Someone can give me a tip? Thanks!

推荐答案

我相信一种标准的方法是使用 facade 模式来包装配置管理器,然后你就有了一些松散耦合的东西你可以控制.

I believe one standard approach to this is to use a facade pattern to wrap the configuration manager and then you have something loosely coupled that you have control over.

因此您将包装 ConfigurationManager.类似的东西:

So you would wrap the ConfigurationManager. Something like:

public class Configuration: IConfiguration
{
    public User
    {
        get
        { 
            return ConfigurationManager.AppSettings["User"];
        }
    }
}

(您可以从配置类中提取一个接口,然后在代码中的任何地方使用该接口)然后你只需模拟 IConfiguration.您也许能够以几种不同的方式实现外观本身.上面我选择只是包装各个属性.您还可以获得使用强类型信息而不是弱类型哈希数组的附带好处.

(You can just extract an interface from your configuration class and then use that interface everywhere in your code) Then you just mock the IConfiguration. You might be able to implement the facade itself in a few different ways. Above I chose just to wrap the individual properties. You also obtain the side benefit of having strongly typed information to work with rather than weakly typed hash arrays.

这篇关于如何使用 moq 模拟 ConfigurationManager.AppSettings的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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