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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public IConfigurationRoot BuildConfiguration(string testDirectory) | |
{ | |
return new ConfigurationBuilder() | |
.SetBasePath(testDirectory) | |
.AddJsonFile("appsettings.json", optional: true) | |
.Build(); | |
} |
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):
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[TestFixture] | |
public class Tests | |
{ | |
private IConfiguration _configuration; | |
[OneTimeSetUp] | |
public void Init() | |
{ | |
_configuration=BuildConfiguration(TestContext.CurrentContext.TestDirectory); | |
} | |
} |
Remark: Don’t forget to set the appsettings.json file properties to ‘Copy Always’