I am trying to do the following in an XUnit project to get the connectionstring to the database my tests should be using:
public class TestFixture : IDisposable
{
public IConfigurationRoot Configuration { get; set; }
public MyFixture()
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
}
public void Dispose()
{
}
}
It is very strange because it works perfectly in the WebAPI and MVC templates when used in Startup.cs. Additionally, this code was previously working in RC1 with dnx, but now that I updated everything to RC2 and Core CLI it no longer is able to find the appsettings.json
file which is in the root of the xunit class library.
Here is what my test class looks like so you can see how I am calling for the configuration:
public class MyTests : IClassFixture<MyFixture>
{
private readonly MyFixture _fixture;
public MyTests(MyFixture fixture)
{
this._fixture = fixture;
}
[Fact]
public void TestCase1()
{
ICarRepository carRepository = new CarRepository(_fixture.Configuration);
}
}
This is a simple issue, you need to have the appsetting.json
also exist under the xunit project. Or you need to use a relative path pointing to where the appsettings.json
exists in the other project.
public class TestFixture : IDisposable
{
public IConfigurationRoot Configuration { get; set; }
public MyFixture()
{
var builder = new ConfigurationBuilder()
.AddJsonFile("../../OtherProj/src/OtherProj/appsettings.json",
optional: true, reloadOnChange: true);
Configuration = builder.Build();
}
public void Dispose() { }
}
Ideally, you'd simply have your own config file local to the test project. In my ASP.NET Core RC2 database test project, my fixture looks like this:
public DatabaseFixture()
{
var builder =
new ConfigurationBuilder()
.AddJsonFile("testsettings.json")
.AddEnvironmentVariables();
// Omitted...
}
Where the testsettings.json
is the test specific config, local to the project.
Update
In your project.json
ensure that you're marking the appsettings.json
as copyToOutput
. Look at the schema store for the details.
"buildOptions": {
"copyToOutput": {
"include": [ "appsettings.json" ]
}
},