有没有办法为您正在单元测试的类设置配置设置?



我已经为我的测试项目编写了所有逻辑,但是我遇到了尝试在要运行的类中设置配置变量的问题。该类要求将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()行代码的字符串匹配的目录,因此它不会找到我希望它找到的文件。

您需要创建一个服务来为您的类提供配置:

public interface IConfiguration 
{
string WorkingDirectory { get; }
}
public class ConfigurationManagerProvider: IConfiguration 
{
public WorkingDirectory => ConfigurationManager.AppSettings["WorkingDirectory"];
}

然后将IConfiguration服务注入到类中,并让该类从此服务获取其配置。 现在,您可以通过模拟此接口或创建第二个实现来提供替代配置。

最新更新