最近,我想出了单元测试来检查我的ASP.NET Core 2.1应用程序的一些重定向规则:
[Fact(DisplayName = "lowercase path")]
public async Task LowercaseRedirect()
{
var result = await this.Client.GetAsync("/BLOG/");
Assert.EndsWith("/blog/", result.RequestMessage.RequestUri.PathAndQuery, StringComparison.InvariantCulture);
}
[Fact(DisplayName = "add missing slash")]
public async Task SlashRedirect()
{
var result = await this.Client.GetAsync("/blog");
Assert.EndsWith("/blog/", result.RequestMessage.RequestUri.PathAndQuery, StringComparison.InvariantCulture);
}
仅供参考:我目前正在将WebApplicationFactory<TEntryPoint>
注入到我的测试类中,该类用于创建HttpClient
。
但是现在我很好奇如何检查https重定向是否有效。任何想法如何做到这一点?在此先感谢:)
答案 0 :(得分:3)
对于UseHttpsRedirection
,中间件必须具有可用的端口才能重定向到HTTPS。如果没有可用端口,则不会重定向到HTTPS。
可以通过以下任意设置指定HTTPS端口:
要测试UseHttpsRedirection
,请指定https端口。您可以按照以下步骤操作:
使用WebApplicationFactory
配置https_port
public class UnitTest1 : IClassFixture<WebApplicationFactory<CoreHttps.Startup>>
{
private readonly WebApplicationFactory<CoreHttps.Startup> _factory;
public UnitTest1(WebApplicationFactory<CoreHttps.Startup> factory)
{
_factory = factory.WithWebHostBuilder(builder => builder
.UseStartup<Startup>()
.UseSetting("https_port", "8080"));
}
默认情况下,请求url为http://localhost/
,如果客户端未自动重定向,请检查请求url。
[Theory]
[InlineData("/Home")]
public async Task HttpsRedirectionWithoutAutoRedirect(string url)
{
// Arrange
var client = _factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
// Act
var response = await client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.RedirectKeepVerb, response.StatusCode);
Assert.StartsWith("http://localhost/",
response.RequestMessage.RequestUri.AbsoluteUri);
Assert.StartsWith("https://localhost:8080/",
response.Headers.Location.OriginalString);
}
如果请求是自动重定向的,请检查请求url。
[Theory]
[InlineData("/Home")]
public async Task HttpsRedirectionWithAutoRedirect(string url)
{
// Arrange
var client = _factory.CreateClient();
// Act
var response = await client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.StartsWith("https://localhost:8080/",
response.RequestMessage.RequestUri.AbsoluteUri);
}