gpt4 book ai didi

c# - 如何使用 moq 从 IConfiguration 模拟 GetConnectionString()?

转载 作者:行者123 更新时间:2023-12-03 15:54:34 26 4
gpt4 key购买 nike

研究: Mocking IConfiguration from .NET Core
我需要对我的数据访问层进行集成测试,以确保所有代码都能正常工作。
我知道它不会以正常方式工作:

//Will return a NotSupportedException
var mock = new Mock<IConfiguration>();
mock.Setup(arg => arg.GetConnectionString(It.IsAny<string>()))
.Returns("testDatabase");
通常,数据访问层使用依赖注入(inject),它使用 IConfiguration 检索连接字符串。 .
我的集成测试:
[Fact]
public async void GetOrderById_ScenarioReturnsCorrectData_ReturnsTrue()
{
// Arrange
OrderDTO order = new OrderDTO();
// Mocking the ASP.NET IConfiguration for getting the connection string from appsettings.json
var mockConfSection = new Mock<IConfigurationSection>();
mockConfSection.SetupGet(m => m[It.Is<string>(s => s == "testDB")]).Returns("mock value");

var mockConfiguration = new Mock<IConfiguration>();
mockConfiguration.Setup(a => a.GetSection(It.Is<string>(s => s == "ConnectionStrings:testDB"))).Returns(mockConfSection.Object);

IDataAccess dataAccess = new SqlDatabase(mockConfiguration.Object);
IRepository repository = new repository(dataAccess, connectionStringData);
var connectionStringData = new ConnectionStringData
{
SqlConnectionLocation = "testDatabase"
};

// Act
int id = await repository.CreateOrder(order);

// Assert
Assert.Equal(1, id);
}
但我得到一个错误

System.InvalidOperationException: The ConnectionString property has not been initialized.


我有点迷路了,我不确定发生了什么。

最佳答案

尝试改变:

 mockConfiguration.Setup(a => a.GetSection(It.Is<string>(s => s == "ConnectionStrings:testDB"))).Returns(mockConfSection.Object);
到:
 mockConfiguration.Setup(a => a.GetSection(It.Is<string>(s => s == "ConnectionStrings"))).Returns(mockConfSection.Object);
下一个设置打印“模拟值”:
var mockConfSection = new Mock<IConfigurationSection>();
mockConfSection.SetupGet(m => m[It.Is<string>(s => s == "testDB")]).Returns("mock value");

var mockConfiguration = new Mock<IConfiguration>();
mockConfiguration.Setup(a => a.GetSection(It.Is<string>(s => s == "ConnectionStrings"))).Returns(mockConfSection.Object);

Console.WriteLine(mockConfiguration.Object.GetConnectionString("testDB")); // prints "mock value"

关于c# - 如何使用 moq 从 IConfiguration 模拟 GetConnectionString()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62503321/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com