如何对调用IConfiguration.Get <T>扩展名的方法进行单元测试

Eti*_*and 1 c# unit-testing asp.net-core asp.net-core-configuration

我有一个非常简单的方法,需要对它进行单元测试。

public static class ValidationExtensions
{
    public static T GetValid<T>(this IConfiguration configuration)
    {
        var obj = configuration.Get<T>();
        Validator.ValidateObject(obj, new ValidationContext(obj), true);
        return obj;
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是这configuration.Get<T>是静态扩展方法,不属于IConfiguration。我无法更改该静态方法的实现。

我在想,也许最简单的方法是创建内存配置提供程序?但是我不知道是否可以在不将其绑定到Web主机的情况下创建一个。

Nko*_*osi 6

配置模块独立于与Web主机相关的功能。

您应该能够创建一个内存配置以进行测试,而无需将其绑定到Web主机。

查看以下示例测试

public class TestConfig {
    [Required]
    public string SomeKey { get; set; }
    [Required] //<--NOTE THIS
    public string SomeOtherKey { get; set; }
}

//...

[Fact]
public void Should_Fail_Validation_For_Required_Key() {
    //Arrange
    var inMemorySettings = new Dictionary<string, string>
    {
        {"Email:SomeKey", "value1"},
        //{"Email:SomeOtherKey", "value2"}, //Purposely omitted for required failure
        //...populate as needed for the test
    };

    IConfiguration configuration = new ConfigurationBuilder()
        .AddInMemoryCollection(inMemorySettings)
        .Build();

    //Act
    Action act = () => configuration.GetSection("Email").GetValid<TestConfig>();

    //Assert
    ValidationException exception = Assert.Throws<ValidationException>(act);
    //...other assertions of validation results within exception object
}
Run Code Online (Sandbox Code Playgroud)

我认为这将接近集成测试,但理想情况下,您只是在使用框架相关的功能,以隔离扩展方法的测试。