简体   繁体   English

如何在 xunit 测试项目中读取 appsettings.json?

[英]How to read appsettings.json in xunit test project?

I am trying to write the test cases for one of the method written in MVC controller and in that method I am reading AppSettings.json file.我正在尝试为在 MVC 控制器中编写的方法之一编写测试用例,在该方法中我正在读取 AppSettings.json 文件。 as below如下

public class MemberController : ControllerBase
{
    IMemberRepository _memberRepository;
    public PayPalKeys payPal;
    public ActiveDirectory activeDirectory;
    private static GraphServiceClient _graphServiceClient;
    public MemberController(IMemberRepository member, IOptions<PayPalKeys> payPal, IOptions<ActiveDirectory> activeDirectory)
    {
        _memberRepository = member;
        this.payPal = payPal.Value;
        this.activeDirectory = activeDirectory.Value;
    }   
    
    private IConfigurationRoot LoadAppSettings()
    {
        try {
            var config = new ConfigurationBuilder()
            .SetBasePath(System.IO.Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", false, true)
            .Build();
            -
            -
            -
        }
        catch(Exception ae){}
    }
}

and the below is my Test code下面是我的测试代码

[Fact]
public void Payment()
{
    var memberRepositoryManagerMock = new Mock<IMemberRepository>();     
    var members = new Members() {};
    var controller = new MemberController(memberRepositoryManagerMock.Object, GetPayPalConfigurationMock().Object, GetActiveDirectoryConfigurationMock().Object);
    var result = controller.MakePayment(members);
}

and that method from controller gives the exception as The configuration file 'appsettings.json' was not found and is not optional.并且来自控制器的该方法给出了异常,因为未找到配置文件“appsettings.json”并且不是可选的。 The physical path is 'F:\\API.Test\\bin\\Debug\\netcoreapp2.2\\appsettings.json'.物理路径是“F:\\API.Test\\bin\\Debug\\netcoreapp2.2\\appsettings.json”。

Here I am not understanding that how to mock that "appsettings.json" part in the test case code.在这里,我不明白如何在测试用例代码中模拟“appsettings.json”部分。

Right click on the settings file in Visual Studio and set the "Copy to Output Directory" to "Copy always" or "Copy when never".右键单击 Visual Studio 中的设置文件,将“复制到输出目录”设置为“始终复制”或“从不复制”。

在此处输入图片说明

To be more precise of the file location, change your configuration-builder to do that:要更精确地确定文件位置,请更改您的配置构建器以执行此操作:

var config = new ConfigurationBuilder()
    .SetBasePath(AppContext.BaseDirectory)
    .AddJsonFile("appsettings.json", false, true)
    .Build();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM