Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 306
Madhav Avatar asked Jun 07 '19 09:06

Madhav


Video Answer


1 Answers

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

enter image description here

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();
like image 90
alsami Avatar answered Sep 16 '22 16:09

alsami