如何将 MSTest 项目使用的 app.config 设置迁移到 .NET 5



我正在迁移一个使用 .NET Framework 4.6.1 的 ASP.NET Web API 解决方案,以 ASP.NET Core 5/.NET Framework 5。除了 Web API 项目之外,还有一个基于 MSTest 的测试项目,该项目与 Web API 项目共享连接字符串信息。这如下所示:

Web API 项目有一个包含以下代码的Web.config文件:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings configSource="binConnectionInfo.config" />
...
</configuration>

基于 MSTest 的项目有一个包含以下代码的App.config文件:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/>
</startup>
<connectionStrings configSource="ConnectionInfo.config"/>
</configuration>

因此,上述两个文件都引用ConnectionInfo.config其中包含实际的连接字符串,如下所示:

<connectionStrings>
<add name="MyConnectionString" connectionString="the connection string" />
</connectionStrings>

该设置可确保我有一个点,我需要在其中更改连接字符串以将应用程序指向另一个数据库。

最终,我在测试数据库中检索连接字符串并将其传递给我的DatabaseManager,该提供了创建和重置数据库的功能:

string connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
_databaseManager = new DatabaseManager(connectionString);

现在,将 Web API 项目迁移到 Core 5 ASP.NET 后,Web.config将替换为appsettings.json文件。每个环境都有一个这样的文件,每个文件都包含该环境的连接字符串。

有没有办法以某种方式与测试项目共享相应的连接字符串?我不想在该项目中手动加载appsettings.json,但希望有一个内置机制。有什么可能有帮助的吗?

通过将 nugetSystem.Configuration.ConfigurationManager包添加到单元测试项目中,可以使用现有app.config来保存连接字符串,就像 .NET 5.0 中的 .NET Framework 中的连接字符串一样,并在 .NET Framework 中像以前一样使用 ConfigurationManager.ConnectionStrings。

最新的稳定版本是 v5.0.0。

另请参阅Nuget页面 https://www.nuget.org/packages/System.Configuration.ConfigurationManager/5.0.0

和文档: https://learn.microsoft.com/en-us/dotnet/api/system.configuration.configurationmanager.connectionstrings?view=windowsdesktop-5.0

有一件事是肯定的,System.Configuration.ConfigurationManagernuget包主要是特定于Windows的,并且在文档中它作为.NET 5.0的"Windows Desktop"的一部分包含在内,而不是.NET 5.0的完整跨平台。

为了从测试项目中读取存储在主项目appsettings.json中的连接字符串,我向其添加了 NuGet 包Microsoft.Extensions.Configuration.Json

然后,我确保主项目将appsettings.json文件复制到输出目录,可以在 .csproj 文件中按以下步骤完成:

<ItemGroup>
<None Include="appsettings.Development.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>

最后,在测试项目中,我通过读取appsettings.json文件来获取连接字符串,如下所示:

protected static readonly string _connectionString = new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile("appsettings.json", false, true)
.Build()
.GetConnectionString("ConnectionStringKeyName");

相关内容

最新更新