Using an app.config file with NUnit3 in a .NET Core console app
For one project testhost.dll.config
is working well.
For another project I had to use testhost.x86.dll.config
The solution from (prd) was very helpfull for verifying the real path being used
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).FilePath;
https://github.com/dotnet/corefx/issues/22101
Copy app.config with correct name
<Target Name="CopyCustomContent" AfterTargets="AfterBuild">
<!-- Command Line (dotnet test) -->
<Copy SourceFiles="App.config" DestinationFiles="$(OutDir)\testhost.dll.config" />
<!-- Visual Studio Test Explorer -->
<Copy SourceFiles="App.config" DestinationFiles="$(OutDir)\testhost.x86.dll.config" />
</Target>
This was another interesting solution
<None Update="App.config">
<Link>testhost.x86.dll.config</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
Rider version > 2020.2 and up looks for ReSharperTestRunner64.dll.config
. So to extend Nathan Smith's answer, have an App.config
and copy it:
<Target Name="CopyCustomContent" AfterTargets="AfterBuild">
<!-- Command Line (dotnet test) -->
<Copy SourceFiles="App.config" DestinationFiles="$(OutDir)\testhost.dll.config" />
<!-- Rider -->
<Copy SourceFiles="App.config" DestinationFiles="$(OutDir)\ReSharperTestRunner64.dll.config"/>
</Target>
When you execute the following line within a unit test and inspect its result, you may notice that the NUnit project looks for a configuration file called testhost.dll.config
.
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).FilePath;
Path shortened:
ClassLibrary1\NUnitTestProject1\bin\Debug\netcoreapp2.2\testhost.dll.config
Thereby, I have created an example of how to use a configuration file with ASP.NET Core 2.2 and the NUnit Test Project template. Also, make sure that the Copy to Output Directory setting for the configuration file is set to Copy always
.
UnitTest.cs
public class UnitTest
{
private readonly string _configValue = ConfigurationManager.AppSettings["test"];
[Test]
public void Test()
{
Assert.AreEqual("testValue", _configValue);
}
}
testhost.dll.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="test" value="testValue" />
</appSettings>
</configuration>