简体   繁体   中英

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. 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. The physical path is '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.

Right click on the settings file in Visual Studio and set the "Copy to Output Directory" to "Copy always" or "Copy when never".

在此处输入图片说明

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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