Hop*_*son 2 c# moq mocking appsettings .net-core
我在 appsettings.json 文件中有一个节点,如下所示
"MyClassName": {
"MyList1": ["x","y"],
"MyList2": ["a","b","c"]
}
Run Code Online (Sandbox Code Playgroud)
为了保存和使用这些列表,我在后端有一个具有 2 个属性的类
public class MyClass
{
public List<string> MyList1 { get; set; }
public List<string> MyList2 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
有一种方法可以IConfiguration像这样使用填充这些属性
_iconfiguration.GetSection("MyClassName").Get<MyClass>();
Run Code Online (Sandbox Code Playgroud)
我需要在 .NET Core 应用程序中模拟上面的代码行。为了进行模拟,我使用 Moq(4.16.1) 我尝试像这样模拟它
_mockConfiguration
.Setup(m => m.GetSection(It.IsAny<string>()).Get<Myclass>())
.Returns(MyClassObject);
Run Code Online (Sandbox Code Playgroud)
但我显然错过了一些东西,因为我收到了不支持的表达式错误。错误说的是这样的
扩展方法(此处:ConfigurationBinder.Get)不得在设置/验证表达式中使用。
有办法实现这一点吗?
您会得到异常,因为Get在本例中是扩展方法,并且最小起订量不会模拟扩展
无需嘲笑IConfiguration。可以使用内存配置构建实际实例以获得所需的行为。
//Arrange
Dictionary<string, string> inMemorySettings =
new Dictionary<string, string> {
{"MyClassName:MyList1:0", "x"},
{"MyClassName:MyList1:1", "y"},
{"MyClassName:MyList2:0", "a"},
{"MyClassName:MyList2:1", "b"},
{"MyClassName:MyList2:2", "c"},
};
IConfiguration configuration = new ConfigurationBuilder()
.AddInMemoryCollection(inMemorySettings)
.Build();
//...
Run Code Online (Sandbox Code Playgroud)
上述内容将允许IConfiguration根据需要使用实例。
参考内存配置提供程序
| 归档时间: |
|
| 查看次数: |
2604 次 |
| 最近记录: |