.NET Core Unit Testing - Mock IOptions

前端 未结 8 912
难免孤独
难免孤独 2020-12-12 17:55

I feel like I\'m missing something really obvious here. I have classes that require injecting of options using the .NET Core IOptions pattern(?). When I unit te

8条回答
  •  渐次进展
    2020-12-12 18:15

    For my system and integration tests I prefer to have a copy/link of my config file inside the test project. And then I use the ConfigurationBuilder to get the options.

    using System.Linq;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    
    namespace SomeProject.Test
    {
    public static class TestEnvironment
    {
        private static object configLock = new object();
    
        public static ServiceProvider ServiceProvider { get; private set; }
        public static T GetOption()
        {
            lock (configLock)
            {
                if (ServiceProvider != null) return (T)ServiceProvider.GetServices(typeof(T)).First();
    
                var builder = new ConfigurationBuilder()
                    .AddJsonFile("config/appsettings.json", optional: false, reloadOnChange: true)
                    .AddEnvironmentVariables();
                var configuration = builder.Build();
                var services = new ServiceCollection();
                services.AddOptions();
    
                services.Configure(configuration.GetSection("Products"));
                services.Configure(configuration.GetSection("Monitoring"));
                services.Configure(configuration.GetSection("Services"));
                ServiceProvider = services.BuildServiceProvider();
                return (T)ServiceProvider.GetServices(typeof(T)).First();
            }
        }
    }
    }
    

    This way I can use the config everywhere inside of my TestProject. For unit tests I prefer to use MOQ like patvin80 described.

提交回复
热议问题