我正在尝试在 XUnit 项目中执行以下操作,以获取我的测试应该使用的数据库的连接字符串:
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()
{
}
}
这很奇怪,因为它在Startup.cs中使用时在WebAPI和MVC模板中完美运行。此外,此代码以前在RC1中使用dnx工作,但现在我将所有内容更新到RC2和Core CLI,它不再能够找到xunit类库的根目录中的appsettings.json
文件。
这是我的测试类的样子,所以你可以看到我如何调用配置:
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);
}
}
答案 0 :(得分:19)
这是一个简单的问题,您需要在 xunit 项目下存在appsetting.json
。或者您需要使用指向另一个项目中appsettings.json
所在位置的相对路径。
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() { }
}
理想情况下,您只需拥有自己的测试项目本地配置文件即可。在我的 ASP.NET Core RC2 数据库测试项目中,我的fixture看起来像这样:
public DatabaseFixture()
{
var builder =
new ConfigurationBuilder()
.AddJsonFile("testsettings.json")
.AddEnvironmentVariables();
// Omitted...
}
testsettings.json
是测试特定配置,项目的本地配置。
<强>更新强>
在project.json
中,确保您将appsettings.json
标记为copyToOutput
。请查看schema store了解详细信息。
"buildOptions": {
"copyToOutput": {
"include": [ "appsettings.json" ]
}
},
答案 1 :(得分:4)
为@DavidPine的回答添加更多信息
不知何故,相对路径对我不起作用,所以我就是这样做的。
var builder = new ConfigurationBuilder()
.SetBasePath(Path.GetFullPath(@"../XXXX")).AddJsonFile("appsettings.json");
我是.net core 1.0.0-preview1-002702