首页 > 解决方案 > 有没有办法为您正在单元测试的类设置配置设置?

问题描述

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

标签: c#unit-testingconfigurationmanager

解决方案


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

public interface IConfiguration 
{
    string WorkingDirectory { get; }
}

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

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


推荐阅读