我正在關注此guide。我在使用appsettings.json
配置文件的API項目中有Startup
。AppSettings.json用於ASP.NET Core中的集成測試
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
文件),因此測試在創建TestServer
。
我試圖通過修改測試project.json
文件來解決這個問題。
"buildOptions": {
"emitEntryPoint": true,
"copyToOutput": {
"includeFiles": [
"appsettings.json"
]
}
}
我希望這將在appsettings.json
文件複製到構建輸出目錄,但抱怨的項目缺少一個入口點Main
方法,治療像一個控制檯項目的測試項目。
我能做些什麼來解決這個問題?難道我做錯了什麼?
根據我的理解:在測試過程中,當您使用目標應用程序根目錄作爲內容根目錄和/或基本路徑(而不是測試輸出目錄)時,應用程序'Startup'將使用自己的'appsettings.json',在測試之外。在這種情況下,將測試項目'appsettings.json'複製到其輸出目錄將不起作用。該json文件將不會被讀取。那是你的經歷嗎? – superjos