我有一个使用xUnit
和FluentAssertions
框架的ASP.NET Core 2.2 WebAPI。它创建一个Microsoft.AspNetCore.TestHost.TestServer
,然后使用HttpClient
API从该服务器对象创建一个Microsoft.AspNetCore.TestHost.TestServer.CreateClient()
。
单元测试在使用Visual Studio 2017 Pro的本地Windows 10计算机上运行良好。我提交了代码,然后发出了请求请求。拉取请求会自动启动构建过程以确保构建成功。构建完成后,它会寻找并运行单元测试。在这一点上它失败了。我有242个单元测试。所有242单元测试均失败,并由代理报告完全相同的错误:
Expected resp.StatusCode to be OK, but found TemporaryRedirect.
[所有242个单元测试都向测试服务器发出请求,因此它们都期望HttpStatusCode.OK
(或类似期望的)响应。我永远不要指望HttpStatuscode.TemporaryRedirect
,所以我真的不想为此添加测试用例。
构建服务器作为Microsoft Server 2012 R2在VSTS中运行,并安装了Visual Studio 2017 Pro。
为什么TestServer
对象会返回重定向?
如果没有解决方法,我可以在HttpClient
收到此状态后强制其自动重定向,以便仅获得API调用的结果吗?
这是我用来创建服务器和客户端的代码:
var config = new ConfigurationBuilder()
.SetBasePath(Path.GetFullPath("../../../../XXXXXXXXService/"))
.AddJsonFile("appsettings.json", optional: false)
.Build();
_server = new TestServer(new WebHostBuilder().UseStartup<Startup>().UseConfiguration(config));
TestHttpClient = _server.CreateClient();
失败的示例单元测试:
private string DeriveHttpPath(string path) =>
$"/{_rootPath.Trim('/')}/{path.TrimStart('/')}";
private static async Task<TResult> ValidateAndReadResponseAsync<TResult>(
HttpResponseMessage resp, HttpStatusCode statusShouldBe, Func<TResult> defFactory = null)
{
(resp.IsSuccessStatusCode ? HttpStatusCode.OK : resp.StatusCode).Should().Be(statusShouldBe);
try
{
return await resp.Content.ReadAsAsync<TResult>();
}
catch (Exception ex)
{
return defFactory != null ? defFactory.Invoke() : throw ex;
}
}
public async Task<TResult> GetDocumentDataAsync<TResult>(string documentId,
string path = null, HttpStatusCode statusShouldBe = HttpStatusCode.OK)
{
using (var msg = new HttpRequestMessage(HttpMethod.Get,
DeriveHttpPath($"{_collectionId}/{documentId}?path={path}")))
using (var resp = await _httpClient.SendAsync(msg))
{
return await ValidateAndReadResponseAsync<TResult>(resp, statusShouldBe);
}
}
_rootPath
将是控制器的根,即:/api/MyController
谢谢您的帮助。
#if !DEBUG
app.UseHttpsRedirection();
#endif
因此,当我在本地运行单元测试时,它被编译为Debug,在将其推送到构建服务器时,它被编译为Release并打开了Https-Redirection。
我通过在Azure中进行设置来取出该代码,并将WebAPI仅设置为HTTPS。