当抛出HttpException时,如何编写单元测试来检查http状态代码?

时间:2015-04-07 09:21:50

标签: c# unit-testing

我正在编写一个API客户端,当请求不成功时,它应该使用适当的HTTP状态代码抛出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.");
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您可以在单元测试中使用try-catch语句测试HTTP状态代码。看来你不能将try-catch方法与ExpectedException()属性混合使用。如果您这样做,您将收到如下消息:

  

测试方法没有抛出异常。一个   属性预计会出现异常   Microsoft.VisualStudio.TestTools.UnitTesting.ExpectedExceptionAttribute   在测试方法上定义。

但是,您可以在常规单元测试中捕获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();
    }
}