Cod*_*ure 5 c# unit-testing moq asp.net-core
研究: 从 .NET Core 模拟 IConfiguration
我需要对我的数据访问层进行集成测试,以确保所有代码都能正常工作。
我知道它不会使用正常方式工作:
//Will return a NotSupportedException
var mock = new Mock<IConfiguration>();
mock.Setup(arg => arg.GetConnectionString(It.IsAny<string>()))
.Returns("testDatabase");
Run Code Online (Sandbox Code Playgroud)
通常,数据访问层使用依赖注入并使用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);
}
Run Code Online (Sandbox Code Playgroud)
但我收到一个错误
System.InvalidOperationException: ConnectionString 属性尚未初始化。
我有点迷失在这里,我不确定发生了什么。
Try changing :
mockConfiguration.Setup(a => a.GetSection(It.Is<string>(s => s == "ConnectionStrings:testDB"))).Returns(mockConfSection.Object);
Run Code Online (Sandbox Code Playgroud)
To:
mockConfiguration.Setup(a => a.GetSection(It.Is<string>(s => s == "ConnectionStrings"))).Returns(mockConfSection.Object);
Run Code Online (Sandbox Code Playgroud)
Next setup prints "mock value":
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"
Run Code Online (Sandbox Code Playgroud)