Search code examples
c#unit-testing

How do I get a c# Unit Test to use App.Config?


I have reduced this to the simplest possible.

VS2019 MSTest Test Project (.NET Core) template

Default unit test project .

Use nuget to install System.Configuration.ConfigurationManager(5.0.0)

Add app.config file to project (add -> new Item -> select Application Configuration File>

Add entry to config file.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
  <add key="TestKey" value="testvalue"/>
</appSettings>
</configuration>

Debug the code below and k is null.

   using Microsoft.VisualStudio.TestTools.UnitTesting;
   using System.Configuration;

   namespace UnitTestProject1
   {
    [TestClass]
    public class UnitTest1
    {
    [TestMethod]
    public void TestMethod1()
    {
        var k = System.Configuration.ConfigurationManager.AppSettings["TestKey"];

    }
  }
 

How do you get the unit test to read the config file?


Solution

  • You have to tell the configuration manager what file to load. Don't rely on the file matching the exe name, etc. Just keep the name as app.config.

    System.Configuration.ConfigurationFileMap configMap = new ConfigurationFileMap("./app.config");
    System.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenMappedMachineConfiguration(configMap);
    string value = configuration.AppSettings["TestKey”];