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

编程入门 行业动态 更新时间:2024-10-19 23:40:55
本文介绍了如何对调用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;的方法进行单元测试扩大

本文发布于:2023-11-14 15:19:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1587784.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单元测试   方法   amp   IConfiguration   gt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!