[英]AppSettings.json for Integration Test in ASP.NET Core
我正在遵循本指南 。 我有一個Startup
的一個使用的API項目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
文件)因此測試在創建TestServer
失敗。
我嘗試通過修改測試project.json
文件來解決這個問題。
"buildOptions": {
"emitEntryPoint": true,
"copyToOutput": {
"includeFiles": [
"appsettings.json"
]
}
}
我希望這會將appsettings.json
文件復制到構建輸出目錄,但它抱怨項目缺少一個入口點的Main
方法,將測試項目appsettings.json
控制台項目。
我該怎么做才能解決這個問題? 難道我做錯了什么?
ASP.NET.Core 2.0上的集成測試遵循MS指南 ,
您應該右鍵單擊appsettings.json
將其屬性Copy to Output directory
為Copy always
現在你可以在輸出文件夾中找到json文件,然后用它構建TestServer
var projectDir = GetProjectPath("", typeof(TStartup).GetTypeInfo().Assembly);
_server = new TestServer(new WebHostBuilder()
.UseEnvironment("Development")
.UseContentRoot(projectDir)
.UseConfiguration(new ConfigurationBuilder()
.SetBasePath(projectDir)
.AddJsonFile("appsettings.json")
.Build()
)
.UseStartup<TestStartup>());
/// Ref: https://stackoverflow.com/a/52136848/3634867
/// <summary>
/// Gets the full path to the target project that we wish to test
/// </summary>
/// <param name="projectRelativePath">
/// The parent directory of the target project.
/// e.g. src, samples, test, or test/Websites
/// </param>
/// <param name="startupAssembly">The target project's assembly.</param>
/// <returns>The full path to the target project.</returns>
private static string GetProjectPath(string projectRelativePath, Assembly startupAssembly)
{
// Get name of the target project which we want to test
var projectName = startupAssembly.GetName().Name;
// Get currently executing test project path
var applicationBasePath = System.AppContext.BaseDirectory;
// Find the path to the target project
var directoryInfo = new DirectoryInfo(applicationBasePath);
do
{
directoryInfo = directoryInfo.Parent;
var projectDirectoryInfo = new DirectoryInfo(Path.Combine(directoryInfo.FullName, projectRelativePath));
if (projectDirectoryInfo.Exists)
{
var projectFileInfo = new FileInfo(Path.Combine(projectDirectoryInfo.FullName, projectName, $"{projectName}.csproj"));
if (projectFileInfo.Exists)
{
return Path.Combine(projectDirectoryInfo.FullName, projectName);
}
}
}
while (directoryInfo.Parent != null);
throw new Exception($"Project root could not be located using the application root {applicationBasePath}.");
}
Ref: TestServer w / WebHostBuilder沒有在ASP.NET Core 2.0上讀取appsettings.json,但它在1.1上工作
最后,我遵循了本指南 ,特別是針對頁面底部的集成測試部分。 這樣就無需將appsettings.json
文件復制到輸出目錄。 相反,它告訴測試項目Web應用程序的實際目錄。
至於將appsettings.json
復制到輸出目錄,我還設法appsettings.json
工作。 結合dudu的答案,我使用include
而不是includeFiles
所以結果部分看起來像這樣:
"buildOptions": {
"copyToOutput": {
"include": "appsettings.json"
}
}
我不完全確定為什么會這樣,但確實如此。 我快速查看了文檔,但找不到任何真正的差異,因為原來的問題基本上解決了,所以我沒有進一步看。
在test project.json
文件中刪除"emitEntryPoint": true
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.