我正在按照这个指南进行操作。在API项目中,我有一个Startup
使用了appsettings.json
配置文件。
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.ReadFrom.Configuration(Configuration)
.CreateLogger();
}
我关注的特定部分是 env.ContentRootPath
。我进行了一些调查,发现我的 appsettings.json
实际上没有复制到 bin
文件夹中,但这没关系,因为 ContentRootPath
返回的是 MySolution\src\MyProject.Api\
,这就是 appsettings.json
文件所在的位置。
因此,在我的集成测试项目中,我有以下测试:
public class TestShould
{
private readonly TestServer _server;
private readonly HttpClient _client;
public TestShould()
{
_server = new TestServer(new WebHostBuilder().UseStartup<Startup>());
_client = _server.CreateClient();
}
[Fact]
public async Task ReturnSuccessful()
{
var response = await _client.GetAsync("/monitoring/test");
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
Assert.Equal("Successful", responseString);
}
这基本上是从指南中复制和粘贴的。当我调试这个测试时,ContentRootPath
实际上是MySolution\src\MyProject.IntegrationTests\bin\Debug\net461\
,这显然是测试项目的生成输出文件夹,而且appsettings.json
文件也不在那里(是的,我确实在测试项目本身中有另一个appsettings.json
文件),因此测试失败了。
我试图通过修改测试的project.json
文件来解决这个问题。
"buildOptions": {
"emitEntryPoint": true,
"copyToOutput": {
"includeFiles": [
"appsettings.json"
]
}
}
我希望这个操作可以将 appsettings.json
文件复制到生成的输出目录,但是它抱怨该项目缺少一个用于入口点的 Main
方法,将测试项目视为控制台项目。
我应该如何解决这个问题?我做错了什么吗?
contentRoot
是您的.csproj文件所在的位置。我使用https://dev59.com/FlQK5IYBdhLWcg3wQt5t#52136848中的“GetProjectPath”。 - John Jang