为什么我的 API 测试在应该通过时却失败了

Why does my API test fails when it should pass

我是 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 响应。

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);
}