我已经为测试项目编写了所有逻辑,但是我遇到了尝试在要运行的类中设置配置变量的问题。该类要求将workingDirectory
变量设置为文件路径,具体取决于程序在何种环境下运行(例如,生产或测试),现在该变量为null。如何使配置设置像正常运行该类一样运行(因为在单独运行该类或未对其进行测试时设置了配置设置)?
我尝试将正在测试的类中使用的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”,而应为null或空格。最终将导致错误,因为没有目录与提供给Directory.GetFiles()
代码行的字符串匹配,因此无法找到我想要查找的文件。
答案 0 :(得分:1)
您需要创建一个服务来为您的班级提供配置:
public interface IConfiguration
{
string WorkingDirectory { get; }
}
public class ConfigurationManagerProvider: IConfiguration
{
public WorkingDirectory => ConfigurationManager.AppSettings["WorkingDirectory"];
}
然后将IConfiguration
服务注入您的类,并让该类从该服务获取其配置。现在,您可以通过模拟此接口或创建第二个实现来提供替代配置。