我正在嘗試模擬配置,但 urlVariable 一直回傳 null,我也無法模擬 GetValue,因為它是 Configuration Builder 下的靜態擴展
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"
}
}
}
}
uj5u.com熱心網友回復:
也許您沒有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");
}
}
此外,您可能想探索OptionsPattern
uj5u.com熱心網友回復:
您不需要模擬可以手動創建的東西。
使用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");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/334382.html
