C# 当引发HttpException时,如何编写单元测试来检查http状态代码?
我正在编写一个API客户端,当请求未成功时,它应该抛出一个带有适当HTTP状态代码的C# 当引发HttpException时,如何编写单元测试来检查http状态代码?,c#,unit-testing,C#,Unit Testing,我正在编写一个API客户端,当请求未成功时,它应该抛出一个带有适当HTTP状态代码的System.Web.HttpException。我知道我可以使用[ExpectedException(typeof(HttpException))]属性测试HttpException是否抛出,但这不会告诉我状态代码是否正确。我如何断言状态代码是正确的 这是我的客户: public static async Task<HttpResponseMessage> SubmitRequest(string
System.Web.HttpException
。我知道我可以使用[ExpectedException(typeof(HttpException))]
属性测试HttpException是否抛出,但这不会告诉我状态代码是否正确。我如何断言状态代码是正确的
这是我的客户:
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.");
}
}
}
公共静态异步任务SubmitRequest(字符串端点,字符串apiKey)
{
ServerResponse serverMessage=newserverresponse();
var credentials=Convert.ToBase64String(Encoding.ASCII.GetBytes(String.Format(“{0}:”,apiKey));
使用(var client=new HttpClient())
{
client.BaseAddress=新Uri(“https://localhost/api/v1/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(新的MediaTypeWithQualityHeaderValue(“应用程序/json”);
client.DefaultRequestHeaders.Authorization=新的AuthenticationHeaderValue(“基本”,凭证);
//HTTP获取
HttpResponseMessage response=wait client.GetAsync(端点);
//如果响应状态代码在200-299范围内
if(响应。IsSuccessStatusCode)
{
返回响应;
}
//请求未成功
if(response.StatusCode==HttpStatusCode.Unauthorized)
{
抛出新的HttpException(401,“未授权”);
}
}
}
您可以在单元测试中使用try-catch语句来测试HTTP状态代码。但是,您似乎不能将try-catch方法与ExpectedException()
属性混合使用。如果您这样做,您将收到如下消息:
测试方法未引发异常。一
属性预期出现异常
Microsoft.VisualStudio.TestTools.UnitTesting.ExpectedException属性
定义在测试方法上
但是,您可以在常规单元测试中捕获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();
}
}
我猜你不是在用NUnit吧?它的Assert.Throws和Assert.DoesNotThrow方法对于此类场景非常方便