Testing using ConfigurationManager with .net core

.net core has moved away from web.config and app.config but realistically it’s a pattern that many projects will still want to follow. Fortunately there is help in the form of the System.Configuration.ConfigurationManager NuGet package. However, there is a snag when it comes to using this package with unit testing, it doesn’t work 😉 The problem is that it goes looking for a .config file related to the test host rather than your test project. I’m currently working around this with a quick static hack but the correct answer is to inject a new config. You can correct the path like this;

var myConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).FilePath;            
myConfig = myConfig.Replace("testhost.dll.config", "MyProjectTests.dll");
var config = ConfigurationManager.OpenExeConfiguration(myConfig);

Hope that helps.

Advertisements