Inside my (.NET Core) unit tests I wanted to load my configuration. I created a small helper method that loads my configuration from a json file:
To make this code compile, you have to add 2 NuGet packages to your test project:
- To enable the SetBasePath method: https://www.nuget.org/packages/Microsoft.Extensions.Configuration.FileExtensions/
- To enable the AddJsonFile method: https://www.nuget.org/packages/Microsoft.Extensions.Configuration.Json/
Now you can invoke this method inside your test setup (I’m using NUnit so I use the OneTimeSetUp method) and pass on the TestDirectory (which is through TestContext.CurrentContext.TestDirectory for NUnit):
Remark: Don’t forget to set the appsettings.json file properties to ‘Copy Always’