Populate IConfiguration for unit tests

前端 未结 5 812
别那么骄傲
别那么骄傲 2021-01-17 07:37

.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

5条回答
  •  抹茶落季
    2021-01-17 08:24

    I prefer not to have my application classes dependent on IConfiguration. Instead I create a configuration class to hold the config, with a constructor that can initialise it from IConfiguration like this:

    public class WidgetProcessorConfig
    {
        public int QueueLength { get; set; }
        public WidgetProcessorConfig(IConfiguration configuration)
        {
            configuration.Bind("WidgetProcessor", this);
        }
        public WidgetProcessorConfig() { }
    }
    
    

    then in your ConfigureServices, you just have to do:

    services.AddSingleton();
    services.AddSingleton();
    

    and for testing:

    var config = new WidgetProcessorConfig
    {
        QueueLength = 18
    };
    var widgetProcessor = new WidgetProcessor(config);
    

提交回复
热议问题