AppSettings.json for Integration Test in ASP.NET Core

后端 未结 3 1134
花落未央
花落未央 2020-12-10 01:46

I am following this guide. I have a Startup in the API project that uses an appsettings.json configuration file.

public class Startu         


        
3条回答
  •  时光取名叫无心
    2020-12-10 02:34

    Integration test on ASP.NET.Core 2.0 follow MS guide ,

    You should right click appsettings.json set its property Copy to Output directory to Copy always

    And now you could find the json file in output folder, and build TestServer with

    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());
    
    
    
    /// Ref: https://stackoverflow.com/a/52136848/3634867
    /// 
    /// Gets the full path to the target project that we wish to test
    /// 
    /// 
    /// The parent directory of the target project.
    /// e.g. src, samples, test, or test/Websites
    /// 
    /// The target project's assembly.
    /// The full path to the target project.
    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 doesn't read appsettings.json on ASP.NET Core 2.0, but it worked on 1.1

提交回复
热议问题