【发布时间】:2018-02-05 12:32:22
【问题描述】:
我有一个类,其中有一个无参数构造函数。但是当这个构造函数被调用时,类有五个属性从构造函数的配置文件中获取值。类中有两个方法使用在构造函数中初始化的参数。
我想使用模拟框架为两种方法编写单元测试。但是,我不确定如何初始化构造函数中的参数,因为调用该方法不会为这些属性提供值。
public class ABC
{
public ABC()
{
a = ConfigurationManager.AppSetting["GetValue"];
b = ConfigurationManager.AppSetting["GetValue1"];
}
public int Method1(IDictionary<string, string> dict)
{
d = a + b /2; (how to mock values of a and b while writing unit tests
using mock framework. In reality, a in my case is
dictionary)
//some business logic
return d;
}
}
提前致谢,
【问题讨论】:
-
由于构造函数与
ConfigurationManager紧密耦合,因此没有模拟,但是您可以将所需的键/值对添加到单元测试的 app.config 中。鉴于提供的信息非常稀疏,不能说更多。提供minimal reproducible example,可用于复制实际问题并帮助构建可能的解决方案 -
在配置管理器周围使用包装器并模拟包装器类型。见here
标签: unit-testing c#-4.0 moq moq-3