如何模拟 IConfiguration.GetValue<string>



我试图模拟配置,但urlVariable一直返回null,我也无法模拟GetValue,因为它是静态扩展下的配置生成器

public static T GetValue<T>(this IConfiguration configuration, string key); 

这是我到目前为止尝试的

// Arrange
var mockIConfigurationSection = new Mock<IConfigurationSection>();
mockIConfigurationSection.Setup(x => x.Value).Returns("SomeUrl");
mockIConfigurationSection.Setup(x => x.Key).Returns("Url");
var configuration = new Mock<IConfiguration>();
configuration.Setup(c => c.GetSection(It.IsAny<String>())).Returns(mockIConfigurationSection.Object);
// Act
var result = target.Test();

的方法
public async Task Test()
{
var urlVariable = this._configuration.GetValue<string>("Url");
}

试图模仿应用程序设置

{
"profiles": {
"LocalDB": {
"environmentVariables": {
"Url" : "SomeUrl"
}
}
}
}

您不需要模拟可以手动创建的东西。
使用ConfigurationBuilder设置期望值

[Fact]
public void TestConfiguration()
{
var value = new KeyValuePair<string, string>(
"profiles:LocalDb:environmentVariable:Url", 
"http://some.url"
);            
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new[] { value })
.Build();
var actual = 
configuration.GetValue<string>("profiles:LocalDb:environmentVariable:Url");
actual.Should().Be("http://some.url");
}

可能您没有正确实例化target。这段代码应该可以工作。

void Main()
{
// Arrange
var mockIConfigurationSection = new Mock<IConfigurationSection>();
mockIConfigurationSection.Setup(x => x.Value).Returns("SomeUrl");
mockIConfigurationSection.Setup(x => x.Key).Returns("Url");
var configuration = new Mock<IConfiguration>();
configuration.Setup(c => c.GetSection(It.IsAny<String>())).Returns(mockIConfigurationSection.Object);
var target = new TestClass(configuration.Object);

// Act
var result = target.Test();

//Assert
Assert.Equal("SomeUrl", result);
}
public class TestClass 
{
private readonly IConfiguration _configuration;
public TestClass(IConfiguration configuration) { this._configuration = configuration; }
public string Test()
{
return _configuration.GetValue<string>("Url");
}
}

另外,您可能想要探索optionpattern

相关内容