Skip to content

Instantly share code, notes, and snippets.

@OsirisTerje
Last active November 30, 2022 17:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OsirisTerje/3cf3f7fae7b0ae685275f9e64410196c to your computer and use it in GitHub Desktop.
Save OsirisTerje/3cf3f7fae7b0ae685275f9e64410196c to your computer and use it in GitHub Desktop.
Base class for loading appsettingsconfigurations
using NUnit.Framework;
namespace Fhi.BaseConfigTests;
using System.IO;
using Microsoft.Extensions.Configuration;
public abstract class BaseConfigTests
{
protected IConfigurationRoot Config { get; private set; } = null!;
/// <summary>
/// Use to set primary appsettings file, default is appsettings.json
/// </summary>
protected string AppSettings { get; init; } = "appsettings.json";
/// <summary>
/// Use to set the secondary sub appsettings, like appsettings.test.json, default is empty
/// </summary>
protected string AppSettingsSub { get; init; } = "";
protected BaseConfigTests()
{
}
protected BaseConfigTests(string appSettingsSub)
{
AppSettingsSub = appSettingsSub;
}
[OneTimeSetUp]
public void OneTimeInit()
{
Config = GetIConfigurationRoot(TestContext.CurrentContext.TestDirectory);
}
protected T GetConfiguration<T>(string sectionName) where T : class
{
return Config.GetSection(sectionName).Get<T>();
}
protected IConfigurationRoot GetIConfigurationRoot(string outputPath)
{
VerifyPath(AppSettings);
var builder = new ConfigurationBuilder()
.SetBasePath(outputPath)
.AddJsonFile(AppSettings, optional: false);
if (!string.IsNullOrEmpty(AppSettingsSub))
{
VerifyPath(AppSettingsSub);
builder.AddJsonFile(AppSettingsSub, optional: false);
}
return builder.Build();
void VerifyPath(string appsettings)
{
var path = Path.Combine(outputPath, appsettings);
Assert.That(File.Exists(path), $"Finner ikke {path}");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment