如何对调用IConfiguration.Get< T>的方法进行单元测试扩大 [英] How to Unit Test Method Calling IConfiguration.Get<T> extension

查看:39
本文介绍了如何对调用IConfiguration.Get< T>的方法进行单元测试扩大的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have this very simple method that I need to unit test.

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;
    }
}

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

The problem is that configuration.Get<T> is a static extension method and doesn't belong to IConfiguration. I can't change the implementation of that static method.

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

I'm thinking, perhaps the simplest way is to create a Memory Configuration Provider? But I don't know if I can create one without binding it to a web host.

推荐答案

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

The configuration module is independent of web host related features.

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

You should be able to create an in memory configuration to test against without the need to bind it to a web host.

查看以下示例测试

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
}

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

This in my opinion would be coming close to an integration test, but ideally you are just using framework dependent features in order to isolate the testing of the extension method.

这篇关于如何对调用IConfiguration.Get&lt; T&gt;的方法进行单元测试扩大的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆