c# - 有没有办法为您正在单元测试的类设置配置设置?
问题描述
我已经为我的测试项目编写了所有逻辑,但我遇到了尝试在我想要运行的类中设置配置变量的问题。该类需要workingDirectory
根据程序运行的环境(例如生产或测试)将变量设置为文件路径,而现在该变量为空。如何让配置设置像类正常运行一样运行(因为配置设置是在类单独运行或未测试时设置的)?
我尝试将正在测试的类中使用的 app.config 文件添加到测试项目中,但这仍然不会为我设置配置变量。
private static readonly string WorkingDir = ConfigurationManager.AppSettings["WorkingDirectory"];
var files = Directory.GetFiles($@"{WorkingDir}\in"); //this results in the
//filepath being "C:\in" when testing since the WorkingDir configuration
//variable doesn't get set when the class is called from the test project
<add key="WorkingDirectory" value="\\Test" xdt:Transform="Insert"/>
当类从测试项目运行时,配置变量应为“\Test”,但为空或空格。这最终是一个错误,因为没有与给定Directory.GetFiles()
代码行的字符串匹配的目录,因此它不会找到我希望它找到的文件。
解决方案
您需要创建一个服务来为您的课程提供配置:
public interface IConfiguration
{
string WorkingDirectory { get; }
}
public class ConfigurationManagerProvider: IConfiguration
{
public WorkingDirectory => ConfigurationManager.AppSettings["WorkingDirectory"];
}
然后将IConfiguration
服务注入您的类,并让该类从该服务中获取其配置。您现在可以通过模拟此接口或创建第二个实现来提供替代配置。
推荐阅读
- c# - 使用影子属性的最小起订量测试功能
- julia - 从现有 Project.toml 文件创建环境
- git - 是否有可能在 git rebase 与 master 分支之后,一些提交消失了?
- macos - mac os上为什么要使用brew安装anaconda
- python - 对列表中的所有项目运行函数(将日期列表转换为 Unix 时间戳)
- vba - 使用 VBA 在 Powerpoint 中的一张幻灯片上静音和取消静音多个音频媒体
- java - 方阵乘法与传统方式
- c# - 如何不将英文字母传递给Json
- reactjs - 展开后将图形(树)拟合到屏幕上
- amazon-web-services - 是否可以在向组织添加新账户时自动启用 AWS Config?