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
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.