首页 > 解决方案 > 为什么我的 API 测试应该通过却失败了

问题描述

我是 C# 的新手,我需要通过 API 测试来测试服务器是否有正确的响应。在这里,我尝试更新不存在的 ID=100 的用户:

 public void TestUpdate()
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(mainURL + "/v2/100/");
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "PUT";
            httpWebRequest.Headers.Add(authKey, authValue);
          
       
            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {

                string json = new JavaScriptSerializer().Serialize(new
                {
                    externalDealId = "100",
                    status = "Closed"

                });

                streamWriter.Write(json);
            }

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
            }

            Assert.That(httpResponse.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
         
        }

但是当我运行此测试时,它失败并给出一条消息:
结果消息:System.Net.WebException:远程服务器返回错误:(404)未找到。怎样才能让我的测试通过?我只需要断言这个 ID 错误的请求会从服务器给出 404 响应。

标签: c#restsharp

解决方案


WebException被抛出,因此您可以尝试使用该Assert.Throws方法(可能取决于您正在使用的测试 API)

var we = Assert.Throws<WebException>(() =>
{
    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); // exception is thrown 
});

Assert.AreEqual(WebExceptionStatus.ProtocolError, we.Status);

问题是,这ProtocolError不仅是404不幸的。

HttpClient你可以试试

using (var httpc = new HttpClient())
{
    string json = new JavaScriptSerializer().Serialize(new
    {
        externalDealId = "100",
        status = "Closed"

    });
    var content = new StringContent(json, Encoding.UTF8, "application/json");
    var response = await httpc.PutAsync(url, content);
    Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode);
}


推荐阅读