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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With