[英]How can I write a unit test to check the http status code when HttpException is thrown?
I am coding an API client, which should throw a System.Web.HttpException
with the appropriate HTTP status code when the request is not successful. 我正在编码一个API客户端,当请求失败时,该客户端应使用适当的HTTP状态代码抛出
System.Web.HttpException
。 I know that I can test that HttpException is thrown by using the [ExpectedException(typeof(HttpException))]
attribute, but this won't tell me that the status code was correct. 我知道我可以使用
[ExpectedException(typeof(HttpException))]
属性来测试是否抛出[ExpectedException(typeof(HttpException))]
,但这不会告诉我状态码是正确的。 How can I assert that the status code is correct? 如何断言状态码正确?
Here is my client: 这是我的客户:
public static async Task<HttpResponseMessage> SubmitRequest(string endPoint, string apiKey)
{
ServerResponse serverMessage = new ServerResponse();
var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(String.Format( "{0}:", apiKey)));
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://localhost/api/v1/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Basic", credentials );
// HTTP GET
HttpResponseMessage response = await client.GetAsync(endPoint);
// if response status code is in the range 200-299
if (response.IsSuccessStatusCode)
{
return response;
}
// request was not successful
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
throw new HttpException(401, "Not authorized.");
}
}
}
You can test the HTTP status code by using a try-catch statement in your unit test. 您可以通过在单元测试中使用try-catch语句来测试HTTP状态代码。 It seems that you can't mix the try-catch approach with an
ExpectedException()
attribute though. 看来您不能将try-catch方法与
ExpectedException()
属性混合使用。 If you do, you will get a message like this: 如果这样做,您将收到以下消息:
Test method did not throw an exception.
测试方法未引发异常。 An exception was expected by attribute Microsoft.VisualStudio.TestTools.UnitTesting.ExpectedExceptionAttribute defined on the test method.
测试方法上定义的属性Microsoft.VisualStudio.TestTools.UnitTesting.ExpectedExceptionAttribute应该发生异常。
However, you can catch the HttpException
in a regular unit test, and assert that the status code is correct in the catch block: 但是,您可以在常规单元测试中捕获
HttpException
,并在catch块中断言状态代码正确:
[TestMethod]
public async Task ApiClient_ThrowsHttpException401IfNotAuthorised()
{
//arrange
string apiKey = "";
string endPoint = "payments";
//act
try
{
HttpResponseMessage response = await ApiClient.SubmitRequest(endPoint, apiKey);
}
//assert
catch (HttpException ex)
{
// HttpException is expected
Assert.AreEqual(401, (int)ex.GetHttpCode());
Assert.AreEqual("Not authorized.", ex.Message);
}
catch (Exception)
{
// Any other exception should cause the test to fail
Assert.Fail();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.