App.config not loading in .Net Core MSTests project

I am working on a project, I am trying to transfer several libraries from the .NET Framework 4.5.2 to .NET Core 2, and I had some problems trying to read the deprecated app.config appsettings in unit tests.In order to reduce the problem to a minimal playback scenario, I created the following project in VS2017:

enter image description here

I have an app.config file:

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

And the file UnitTest1.cs:

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

namespace SimpleTestsUnits
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void FromConfigurationManager()
        {
            Assert.AreEqual("20", ConfigurationManager.AppSettings["TestKey"]);
        }
    }
}

And when you create this project, SimpleTestsUnits.dll is created, and SimpleTestsUnits.dll.config is created with the contents of the app.config file in the same folder of the SimpleTestsUnits.dll file.

So, when I run unit test using VS2017, the value of "TestKey" is always zero, and if I debug the configuration of ConfigurationManager.AppSettings, the key will not be loaded there.

: 'Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException' Microsoft.VisualStudio.TestPlatform.TestFramework.dll 'Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException' Microsoft.VisualStudio.TestPlatform.TestFramework.dll, Assert.AreEqual. : < 20 > . :. & ; () >

? ?

+4
1

, . , :

var configLocation = Assembly.GetEntryAssembly().Location;

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

, ConfigurationManager app.config testhost.dll.config . , ( , . ).

, app.config . configSections <configuration>. configSections, , app.config :

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

, testhost.dll. , ConfigurationManager ConfigurationManager.OpenExeConfiguration:

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

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

, , .

+2

Source: https://habr.com/ru/post/1690549/


All Articles