簡體   English   中英

AppSettings.json用於ASP.NET核心中的集成測試

[英]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 directoryCopy 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM