AppSettings.json用于ASP.NET核心中的集成测试

Kev*_*Lee 18 c# configuration integration-testing appsettings 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();
    }
Run Code Online (Sandbox Code Playgroud)

我正在看的特别部分是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);
    }
Run Code Online (Sandbox Code Playgroud)

这基本上是指南中的复制和粘贴.当我调试这个测试时,ContentRootPath实际上MySolution\src\MyProject.IntegrationTests\bin\Debug\net461\,这显然是测试项目的构建输出文件夹,而且appsettings.json文件不存在(是的,我确实appsettings.json在测试项目中有另一个文件)因此测试失败了TestServer.

我尝试通过修改测试project.json文件来解决这个问题.

"buildOptions": {
    "emitEntryPoint": true,
    "copyToOutput": {
        "includeFiles": [
            "appsettings.json"
       ]
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望这会将appsettings.json文件复制到构建输出目录,但它抱怨项目缺少Main入口点的方法,将测试项目视为控制台项目.

我该怎么做才能解决这个问题?难道我做错了什么?

Joh*_*n_J 13

ASP.NET.Core 2.0上的集成测试遵循MS指南,

您应该右键单击appsettings.json将其属性设置Copy to Output directory"始终复制"

现在你可以在输出文件夹中找到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}.");
}
Run Code Online (Sandbox Code Playgroud)

Ref:TestServer w/WebHostBuilder没有在ASP.NET Core 2.0上读取appsettings.json,但它在1.1上工作


Kev*_*Lee 8

最后,我遵循了本指南,特别是针对页面底部的集成测试部分.这样就无需将appsettings.json文件复制到输出目录.相反,它告诉测试项目Web应用程序的实际目录.

至于复制appsettings.json到输出目录,我也设法让它工作.结合dudu的答案,我使用include而不是includeFiles所以结果部分看起来像这样:

"buildOptions": {
    "copyToOutput": {
        "include": "appsettings.json"
    }
}
Run Code Online (Sandbox Code Playgroud)

我不完全确定为什么会这样,但确实如此.我快速查看了文档,但找不到任何真正的差异,因为原来的问题基本上解决了,所以我没有进一步看.

  • 如何在.NET.Core 2.0中做到这一点?`project.json`已被弃用. (3认同)