填充IConfiguration以进行单元测试 [英] Populate IConfiguration for unit tests

查看:155
本文介绍了填充IConfiguration以进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.NET Core配置允许这么多选项来添加值(环境变量,json文件,命令行args)。

.NET Core configuration allows so many options to add values (environment variables, json files, command line args).

我只是想不通并找到一个通过代码填充它的答案。

I just can't figure out and find an answer how to populate it via code.

我正在为扩展配置方法编写单元测试,我认为通过代码在单元测试中填充它会比加载更容易。每个测试专用的json文件。

I am writing unit tests for extension methods to configurations and I thought populating it in the unit tests via code would be easier than loading dedicated json files for each test.

我当前的代码:

  [Fact]
  public void Test_IsConfigured_Positive()
  {

    // test against this configuration
    IConfiguration config = new ConfigurationBuilder()
      // how to populate it via code
      .Build();

    // the extension method to test
    Assert.True(config.IsConfigured());

  }

更新:

一种特殊情况是空节,在json中看起来像这样。

One special case is the "empty section" which would look like this in json.

  {
    "MySection": {
       // the existence of the section activates something triggering IsConfigured to be true but does not overwrite any default value
     }
   }






更新2:


Update 2:

As马修(Matthew)在评论中指出,在json中有一个空白部分会产生与根本没有该部分相同的结果。我列举了一个例子,是的,就是这样。

As Matthew pointed out in the comments having an empty section in the json gives the same result as not having the section at all. I distilled an example and yes, that is the case. I was wrong expecting a different behaviour.

所以我该怎么办,我期望什么?

So what do I do and what did I expect:

我我正在为IConfiguration的2个扩展方法编写单元测试(实际上是由于某些原因,Get ... Settings方法中的值绑定不起作用(但这是一个不同的主题)。它们看起来像这样:

I am writing unit tests for 2 extension methods for IConfiguration (actually because the binding of values in Get...Settings method does not work for some reason (but thats a different topic). They look like this:

  public static bool IsService1Configured(this IConfiguration configuration)
  {
    return configuration.GetSection("Service1").Exists();
  }

  public static MyService1Settings GetService1Settings(this IConfiguration configuration)
  {
    if (!configuration.IsService1Configured()) return null;

    MyService1Settings settings = new MyService1Settings();
    configuration.Bind("Service1", settings);

    return settings;
  }

我的误解是,如果我在appsettings中放置一个空白部分,则 IsService1Configured() 方法将返回 true (现在显然是错误的)。我期望的区别是现在有一个空部分 GetService1Settings()方法返回 null ,而不是我期望的 MyService1Settings 具有所有默认值。

My missunderstanding was that if I place an empty section in the appsettings the IsService1Configured() method would return true (which is obviously wrong now). The difference I expected is with having an empty section now the GetService1Settings() method returns null and not as I expected the MyService1Settings with all default values.

幸运的是,由于我没有空白部分(或现在知道我必须避免这些情况)。这只是我编写单元测试时遇到的一个理论案例。

Fortunately this still works for me since I won't have empty sections (or now know that I have to avoid those cases). It was just one theoretical case I came across while writing the unit tests.

进一步(对于感兴趣的人来说)。

Further down the road (for those interested in).

我该怎么用?基于配置的服务激活/停用。

For what do I use it? Configuration based service activation/deactivation.

我有一个应用程序,其中已编译了一个服务/一些服务。根据部署情况,我需要完全激活/停用服务。这是因为某些(本地或测试设置)无法完全访问完整的基础结构(诸如缓存,指标等辅助服务)。我通过appsettings来做到这一点。如果配置了服务(config部分存在),则将添加该服务。如果config节不存在,则将不使用它。

I have an application which has a service / some services compiled into it. Depending on the deployment I need to activate/deactivate the services completly. This is because some (local or testings setups) do not have full access to a complete infrastructure (helper services like caching, metrics...). And I do that via the appsettings. If the service is configured (the config section exists) it will be added. If the config section is not present it will not be used.

摘录示例的完整代码如下。

The full code for the distilled example is below.


  • 在Visual Studio中从模板(没有HTTPS和身份验证)创建一个名为WebApplication1的新API

  • 删除Startup类和appsettings.Development.json

  • 用下面的代码替换Program.cs中的代码

  • 现在在appsettings.json中,您可以通过添加/删除<$ c $来激活/停用服务c> Service1 和 Service2 部分

  • in Visual Studio create a new API named WebApplication1 from the templates (without HTTPS and Authentication)
  • delete the Startup class and appsettings.Development.json
  • replace the code in Program.cs with the code below
  • now in appsettings.json you can activate/deactivate the services by adding/removing Service1 and Service2 section
  using Microsoft.AspNetCore;
  using Microsoft.AspNetCore.Builder;
  using Microsoft.AspNetCore.Hosting;
  using Microsoft.AspNetCore.Mvc;
  using Microsoft.Extensions.Configuration;
  using Microsoft.Extensions.DependencyInjection;
  using Microsoft.Extensions.Logging;
  using Newtonsoft.Json;
  using System;

  namespace WebApplication1
  {

    public class MyService1Settings
    {
    public int? Value1 { get; set; }
    public int Value2 { get; set; }
    public int Value3 { get; set; } = -1;
    }

    public static class Service1Extensions
    {

    public static bool IsService1Configured(this IConfiguration configuration)
    {
    return configuration.GetSection("Service1").Exists();
    }

    public static MyService1Settings GetService1Settings(this IConfiguration configuration)
    {
    if (!configuration.IsService1Configured()) return null;

    MyService1Settings settings = new MyService1Settings();
    configuration.Bind("Service1", settings);

    return settings;
    }

    public static IServiceCollection AddService1(this IServiceCollection services, IConfiguration configuration, ILogger logger)
    {

    MyService1Settings settings = configuration.GetService1Settings();

    if (settings == null) throw new Exception("loaded MyService1Settings are null (did you forget to check IsConfigured in Startup.ConfigureServices?) ");

    logger.LogAsJson(settings, "MyServiceSettings1: ");

    // do what ever needs to be done

    return services;
    }

    public static IApplicationBuilder UseService1(this IApplicationBuilder app, IConfiguration configuration, ILogger logger)
    {

    // do what ever needs to be done

    return app;
    }

    }

    public class Program
    {

      public static void Main(string[] args)
      {
        CreateWebHostBuilder(args).Build().Run();
      }

      public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
        .ConfigureLogging
          (
          builder => 
            {
              builder.AddDebug();
              builder.AddConsole();
            }
          )
        .UseStartup<Startup>();
        }

      public class Startup
      {

        public IConfiguration Configuration { get; }
        public ILogger<Startup> Logger { get; }

        public Startup(IConfiguration configuration, ILoggerFactory loggerFactory)
        {
        Configuration = configuration;
        Logger = loggerFactory.CreateLogger<Startup>();
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

        // flavour 1: needs check(s) in Startup method(s) or will raise an exception
        if (Configuration.IsService1Configured()) {
        Logger.LogInformation("service 1 is activated and added");
        services.AddService1(Configuration, Logger);
        } else 
        Logger.LogInformation("service 1 is deactivated and not added");

        // flavour 2: checks are done in the extension methods and no Startup cluttering
        services.AddOptionalService2(Configuration, Logger);

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
      }

      // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
      public void Configure(IApplicationBuilder app, IHostingEnvironment env)
      {

        if (env.IsDevelopment()) app.UseDeveloperExceptionPage();

        // flavour 1: needs check(s) in Startup method(s) or will raise an exception
        if (Configuration.IsService1Configured()) {
          Logger.LogInformation("service 1 is activated and used");
          app.UseService1(Configuration, Logger); }
        else
          Logger.LogInformation("service 1 is deactivated and not used");

        // flavour 2: checks are done in the extension methods and no Startup cluttering
        app.UseOptionalService2(Configuration, Logger);

        app.UseMvc();
      }
    }

    public class MyService2Settings
    {
      public int? Value1 { get; set; }
      public int Value2 { get; set; }
      public int Value3 { get; set; } = -1;
    }

    public static class Service2Extensions
    {

    public static bool IsService2Configured(this IConfiguration configuration)
    {
      return configuration.GetSection("Service2").Exists();
    }

    public static MyService2Settings GetService2Settings(this IConfiguration configuration)
    {
      if (!configuration.IsService2Configured()) return null;

      MyService2Settings settings = new MyService2Settings();
      configuration.Bind("Service2", settings);

      return settings;
    }

    public static IServiceCollection AddOptionalService2(this IServiceCollection services, IConfiguration configuration, ILogger logger)
    {

      if (!configuration.IsService2Configured())
      {
        logger.LogInformation("service 2 is deactivated and not added");
        return services;
      }

      logger.LogInformation("service 2 is activated and added");

      MyService2Settings settings = configuration.GetService2Settings();
      if (settings == null) throw new Exception("some settings loading bug occured");

      logger.LogAsJson(settings, "MyService2Settings: ");
      // do what ever needs to be done
      return services;
    }

    public static IApplicationBuilder UseOptionalService2(this IApplicationBuilder app, IConfiguration configuration, ILogger logger)
    {

      if (!configuration.IsService2Configured())
      {
        logger.LogInformation("service 2 is deactivated and not used");
        return app;
      }

      logger.LogInformation("service 2 is activated and used");
      // do what ever needs to be done
      return app;
    }
  }

    public static class LoggerExtensions
    {
      public static void LogAsJson(this ILogger logger, object obj, string prefix = null)
      {
        logger.LogInformation(prefix ?? string.Empty) + ((obj == null) ? "null" : JsonConvert.SerializeObject(obj, Formatting.Indented)));
      }
    }

  }


推荐答案

您可以使用 MemoryConfigurationBuilderExtensions 通过字典提供它。

You can use MemoryConfigurationBuilderExtensions to provide it via a dictionary.

var myConfiguration = new Dictionary<string, string>
{
    {"Key1", "Value1"},
    {"Nested:Key1", "NestedValue1"},
    {"Nested:Key2", "NestedValue2"}
}

var configuration = new ConfigurationBuilder()
    .AddInMemoryCollection(myConfiguration)
    .Build();

这篇关于填充IConfiguration以进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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