研究: 从 .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); …Run Code Online (Sandbox Code Playgroud)