小编Cod*_*ure的帖子

如何使用最小起订量从 IConfiguration 模拟 GetConnectionString()?

研究: 从 .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)

c# unit-testing moq asp.net-core

5
推荐指数
1
解决办法
1812
查看次数

标签 统计

asp.net-core ×1

c# ×1

moq ×1

unit-testing ×1