Net Core集成测试:从其他程序运行Startup.cs和配置 [英] Net Core Integration Test: Run Startup.cs and Configuration from other Program

查看:320
本文介绍了Net Core集成测试:从其他程序运行Startup.cs和配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在创建一个集成单元测试(Xunit),它称为Real Application Startup.cs。

We are creating an Integration Unit test (Xunit), which is calling the Real Application Startup.cs.

由于某种原因,Real项目可以读取配置文件/属性正确,但是从集成测试运行它,它将无法读取它。它不会在下面的Configuration(conf)变量中放置任何内容。我该如何解决?
原因是没有读取,因为它没有读取Net Core 2.2中新的内部依赖项注入,后者读取配置文件。

For some reason, Real project can read Configuration file/property correctly, however running it from the Integration test, it cannot read it. Its not placing anything into Configuration (conf) variable below. How would I resolve this? The reason is its not picking up is its not reading the internal dependency injection new from Net Core 2.2 which reads Configuration file. Trying to use .CreateDefaultBuilder Now.

IntegrationTest1.cs

        TestServer _server = new TestServer(new WebHostBuilder() .UseContentRoot("C:\\RealProject\\RealProject.WebAPI")
            .UseEnvironment("Development")
            .UseConfiguration(new ConfigurationBuilder()
            .SetBasePath("C:\\RealProject\\RealProject.WebAPI")
                .AddJsonFile("appsettings.json")
                .Build())
                .UseStartup<Startup>()
            .UseStartup<Startup>());

Real Project Startup.cs

    public Startup(IConfiguration configuration, IHostingEnvironment hostingEnvironment)
    {
        Configuration = configuration;
        HostingEnvironment = hostingEnvironment;
    }

    public IHostingEnvironment HostingEnvironment { get; }
    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {

        var conf = Configuration;
        IConfiguration appConf = conf.GetSection("ConnectionStrings");
        var connstring = appConf.GetValue<string>("DatabaseConnection");

        services.AddDbContext<DbContext>(a => a.UseSqlServer(connstring));

Appsettings.Json

Appsettings.Json

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "ConnectionStrings": {
    "DatabaseConnection": "Data Source=.;Initial Catalog=ApplicationDatabase;Integrated Security=True"
  }
}


推荐答案

您要做的就是为WebApplication创建一个采用Startup类型的Factory。然后,您可以使用 IClassFixture 界面,与测试类中的所有测试共享该工厂的上下文。

What you want to do is create a Factory for your WebApplication which takes a Startup type. You can then use the IClassFixture interface to share the context of this factory with all of your tests in your test class.

这在实践中看起来是这样的:

How this looks in practice is:

public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<Startup> where TStartup : class
{
    public CustomWebApplicationFactory() { }

    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder
            .ConfigureTestServices(
                services =>
                {
                    services.Configure(AzureADDefaults.OpenIdScheme, (System.Action<OpenIdConnectOptions>)(o =>
                    {
                        // CookieContainer doesn't allow cookies from other paths
                        o.CorrelationCookie.Path = "/";
                        o.NonceCookie.Path = "/";
                    }));
                }
            )
            .UseEnvironment("Production")
            .UseStartup<Startup>();
    }
}


public class AuthenticationTests : IClassFixture<CustomWebApplicationFactory<Startup>>
{
    private HttpClient _httpClient { get; }

    public AuthenticationTests(CustomWebApplicationFactory<Startup> fixture)
    {
        WebApplicationFactoryClientOptions webAppFactoryClientOptions = new WebApplicationFactoryClientOptions
        {
            // Disallow redirect so that we can check the following: Status code is redirect and redirect url is login url
            // As per https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.2#test-a-secure-endpoint
            AllowAutoRedirect = false
        };

        _httpClient = fixture.CreateClient(webAppFactoryClientOptions);
    }

    [Theory]
    [InlineData("/")]
    [InlineData("/Index")]
    [InlineData("/Error")]
    public async Task Get_PagesNotRequiringAuthenticationWithoutAuthentication_ReturnsSuccessCode(string url)
    {
        // Act
        HttpResponseMessage response = await _httpClient.GetAsync(url);

        // Assert
        response.EnsureSuccessStatusCode();
    }
}

我遵循指南在这里以我自己的代码运行。

I followed the guide here to get this working in my own code.

这篇关于Net Core集成测试:从其他程序运行Startup.cs和配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆