我试图通过调用应返回错误消息(json响应)的端点来测试我的API。在Postman中测试时,API确实返回了正确的JSON,我能够看到状态代码不是200.但是,当尝试使用xunit和HttpClient进行测试时,我收到以下错误消息:
System.Net.Http.HttpRequestException : Error while copying content to a stream.
我想弄清楚为什么会这样。在我的API中,我正在检查凭据,如果它们不正确,我将抛出异常。此异常将被全局异常处理程序捕获,该异常处理程序将设置正确的状态代码并创建json响应。
异常处理程序:
public class ExceptionHandler : IExceptionFilter
{
public void OnException(ExceptionContext context)
{
int status = (int)HttpStatusCode.InternalServerError;
String message = context.Exception.Message;
var exception = context.Exception;
if (exception is ArgumentNullException)
{
message = ((ArgumentNullException)exception).ParamName + " is required";
status = (int)HttpStatusCode.BadRequest;
}
if (exception is NotFoundException)
{
message = exception.Message;
status = (int)HttpStatusCode.NotFound;
}
if (exception is AuthenticationException)
{
message = exception.Message;
status = (int)HttpStatusCode.Unauthorized;
}
if (exception is DuplicateEntryException)
{
message = exception.Message;
status = 422; // Unprocessable entity, not supported in HttpStatusCode class
}
HttpResponse response = context.HttpContext.Response;
response.StatusCode = status;
response.ContentType = "application/json";
response.WriteAsync(JsonConvert.SerializeObject(new ErrorMessage(message, (int)status)));
}
}
class ErrorMessage
{
public string Message { get; set; }
public int Code { get; set; }
public ErrorMessage(string message, int code)
{
Message = message;
Code = code;
}
}
集成测试:
[Fact]
public async Task ItReturnsAnErrorWhenCredentialsAreIncorrect()
{
var request = new UserAuthenticationRequest();
request.Username = "JohnDoe";
request.Password = "TestPasswordIncorrect";
var stringPayload = JsonConvert.SerializeObject(request);
var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await _client.PostAsync("api/authentication/GetUserAppToken", httpContent);
Assert.Equal(401, (int)response.StatusCode);
}
任何人都知道为什么会抛出HttpRequestException?
更新
客户端设置:
public AuthenticationControllerTest()
{
_testServer = new TestServer(new WebHostBuilder().UseStartup<TestStartup>());
_client = _testServer.CreateClient();
}
我通过为每个测试方法设置一个新客户端来进行测试。不幸的是,这也没有解决问题
更新2:
我认为它必须对HttpClient设置或我发送的请求消息执行某些操作。我没有使用异常处理程序,而是决定立即从控制器返回BadRequest()。
public BadRequestResult Post([FromBody]UserAuthenticationRequest userAuthenticationRequest)
{
return BadRequest();
}
执行此操作时,我再次收到HttpRequestException,而不是获取状态码为400的HttpResponse。