Reputation: 13945
I'm trying to create my first unit test project in .NET Core. I need to figure out how to get the appsettings.json
configurations into this project.
Following the highest voted response here: Read appsettings json values in .NET Core Test Project
I did the following:
1) Copied the appsettings.json
file from the main project into the unit test project root folder and re-named it appsettings.test.json
2) Using the following code:
public static IConfiguration InitConfiguration()
{
var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.test.json")
.Build();
return config;
}
But that returns this error:
The configuration file 'appsettings.test.json' was not found and is not optional. The physical path is 'C:\Workspace\my_project\XUnitTestProject1\bin\Debug\netcoreapp2.2\appsettings.test.json'.
I'd rather not put this file deeply nested into the bin
folder. Is there some other way I can handle this? Or am I doing something wrong?
Here's the big picture::
using Microsoft.Extensions.Options;
using Shared;
using Xunit;
using Microsoft.AspNetCore.Mvc;
using BusinessLogic;
using DataAccess.Models;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
using System;
using Microsoft.Extensions.Configuration;
namespace XUnitTestProject1
{
public class Customers
{
private readonly IOptions<Configurations> _configurations;
public Customers()
{
try
{
var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.test.json")
.Build();
var config = InitConfiguration();
var clientId = config["Configutrations"]
_configurations = ??? // Still not sure how to do this. Error before this point.
}
catch (Exception ex)
{
var m = ex.Message;
}
}
[Fact]
// all of the actual tests
}
The error happens on this line:
var config = new ConfigurationBuilder....
Upvotes: 2
Views: 5260
Reputation: 13945
In the properties of the appsettings.test.json
file, I had to set the Copy to Output Directory
to Copy if Newer
Reference: https://weblog.west-wind.com/posts/2018/Feb/18/Accessing-Configuration-in-NET-Core-Test-Projects
Upvotes: 2