app.config not beeing loaded in .Net Core MSTests project

MSTest is running as "testhost.dll", which means that ConfigurationManager is reading settings from "testhost.dll.config" when executing under .NET core. It will look for "testhost.dll.config" where the "testhost.dll" is located but it will also also look for "testhost.dll.config" in the location where you have your test dlls.

So copying or renaming your config file in explorer to "testhost.dll.config" will solve the problem.

You can easily automate this by adding the following MSBuild step to the end of the MSTest .csproj file, within the "Project" tag.

<Target Name="CopyAppConfig" AfterTargets="Build" DependsOnTargets="Build">
    <CreateItem Include="$(OutputPath)$(AssemblyName).dll.config">
         <Output TaskParameter="Include" ItemName="FilesToCopy"/>
    </CreateItem>
    <Copy SourceFiles="@(FilesToCopy)" DestinationFiles="$(OutputPath)testhost.dll.config" />
</Target>

Source: (https://github.com/Microsoft/testfx/issues/348#issuecomment-454347131)


When you execute the tests, the entry assembly is not an assembly with your tests. You can check it by adding following line to your test and debugging it:

var configLocation = Assembly.GetEntryAssembly().Location;

In my case configLocation was c:\Users\myusername\.nuget\packages\microsoft.testplatform.testhost\15.3.0-preview-20170628-02\lib\netstandard1.5\testhost.dll

So ConfigurationManager expects to find app.config at testhost.dll.config in specified directory. I've copied it to this location and the test passed ok (after slight modification of the config, see below).

Another problem is that your app.config is not fully correct. configSections element should be the first in <configuration> root. So just remove configSections element as it's empty or adjust your app.config in the following way:

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

Of course, it's a bad way to place config file near testhost.dll. You could change the path from which ConfigurationManager loads application config with ConfigurationManager.OpenExeConfiguration call:

[TestMethod]
public void UnitTest1()
{
    //  Put your Test assembly name here
    Configuration configuration = ConfigurationManager.OpenExeConfiguration(@"SimpleTestsUnits.dll");

    Assert.AreEqual("20", configuration.AppSettings.Settings["TestKey"].Value);
}

But unfortunately this approach requires modification of your code under test.

Tags:

C#

.Net Core