测试项目(MSTest)中涉及到读取App.config 操作(.net6)

发布于:2022-11-16 ⋅ 阅读:(746) ⋅ 点赞:(0)

环境

  • VS2022
  • MSTest项目
  • .Net6版本

问题

在测试过程中发现读取App.config中的连接字符串是null,后经反复测试,发现根本不能读取到app.conf文件。

排查过程

查看Nuget包是否正确

结论: 正确,引用了最新的nuget包,引用配置如下

 <PackageReference Include="System.Configuration.ConfigurationManager" Version="7.0.0" />

查看配置文件是否正确

结论:一切正常,配置文件符合规范,样式如下

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="TEST" value="1"/>
  </appSettings>
  <connectionStrings>
    <add name="ConfDb" connectionString="data source=D:\test.db;version=3;"/>
  </connectionStrings>
</configuration>

解决办法(手动)

在生成目录中(例如 bin\debug)找到生成的配置文件,或者将原来的app.config拷贝过来,重命名为:testhost.dll.config

解决办法(自动)

通过工程的生成后事件进行处理,命令如下

copy $(ProjectDir)App.config $(OutDir)testhost.dll.config

在这里插入图片描述

这样就能自动把app.config拷贝到bin\debug中,并且命名成testhost.dll.config

为什么是这样的呢?

在此感谢网友的文章
https://www.cnblogs.com/niuge/p/11732941.html

*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 as the accepted answer states. *

What is not mentioned is that it will also look for testhost.dll.config in the location where you have your test dlls.

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到