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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With