Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 723
Bob Clegg Avatar asked Oct 22 '25 09:10

Bob Clegg


1 Answers

If you add this line to your TestMethod, it will tell you what is the name of the config file it is expecting to use:

public void TestMethod1()
{
    string path = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).FilePath;
    var k = ConfigurationManager.AppSettings["TestKey"];
}

When I ran it, it called the file "(path-to)\testhost.dll.config", not "App.config". So all I did was rename the file to "testhost.dll.config", change its Build Action to "Content" and "Copy always", ran the unit test, and it gave me the right value in var k.

I can't explain why it would look specifically for that filename, but for some reason it is.

like image 93
Tam Bui Avatar answered Oct 25 '25 00:10

Tam Bui



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!