我们正在创建一个集成单元测试 (Xunit),它调用 Real Application Startup.cs。
由于某种原因,真实项目可以正确读取配置文件/属性,但是从集成测试运行它,它无法读取它。它没有将任何内容放入下面的配置(conf)变量中。我该如何解决这个问题?
原因是它没有读取是因为它没有读取 Net Core 2.2 中新的内部依赖注入,它读取配置文件。尝试立即使用 .CreateDefaultBuilder。
集成测试1.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>());
真实项目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));
应用程序设置.Json
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionStrings": {
"DatabaseConnection": "Data Source=.;Initial Catalog=ApplicationDatabase;Integrated Security=True"
}
}
您想要做的是为您的 WebApplication 创建一个采用 Startup 类型的工厂。然后您可以使用IClassFixture https://xunit.net/docs/shared-context#class-fixture接口与测试类中的所有测试共享该工厂的上下文。
这在实践中看起来是这样的:
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://learn.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();
}
}
我跟着导游here https://fullstackmark.com/post/20/painless-integration-testing-with-aspnet-core-web-api让它在我自己的代码中工作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)