我已经设置了一个集成测试:
public class IntegrationTests
{
private readonly TestServer _server;
private readonly HttpClient _client;
public IntegrationTests()
{
_server = new TestServer(WebHost.CreateDefaultBuilder().UseEnvironment("Development").UseStartup<Startup>())
{
PreserveExecutionContext = true,
};
_client = _server.CreateClient();
}
[Test]
public async Task RunARoute()
{
var response = await _client.GetAsync("/foo");
Check.That(response.IsSuccessStatusCode).IsTrue();
}
}
启动:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews()
.AddApplicationPart(typeof(HomeController).Assembly)
.AddControllersAsServices()
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services
.ConfigureAll(Configuration) // Add the configuration sections
.AddAllServices() // DI
// Other:
.AddAutoMapperProfiles(AutoMapperConfiguration.LoadConfig)
.AddCacheHelper(e => {})
.AddSession(opt => opt.Cookie.IsEssential = true);
}
public void Configure(IApplicationBuilder app)
{
app.UseHttpsRedirection()
.UseStaticFiles()
.UseRouting()
.UseCookiePolicy()
.UseSession()
.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
"default",
"{controller=Home}/{action=Index}/{id?}");
});
}
在测试方法中,我调用的路由重定向到另一个路由:return RedirectToAction(nameof(Bar))
. 我想测试该Bar
方法是否正确返回了页面,但不幸的是,该页面HttpClient
没有重定向调用:我的测试失败并显示代码302
。
我在 Internet 上读到,当尝试从 HTTPS 路由重定向到 HTTP 路由时,通常会发生此问题,但是 AFAIK,这里不是这种情况,因为测试服务器使用基本 URL 创建客户端http://localhost/
,并且重定向 URL 是相对的(因此没有指定协议)。
如何确保客户端重定向呼叫?