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

环境

  • 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.

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值