Search code examples
c#restsharp

Why does my API test fails when it should pass


I'm new in C# and I need to test that I have proper response from the server with API test. Here I'm trying to update user with ID=100 who doesn't exist:

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

But when I run this test it fails and gives a message:
Result Message: System.Net.WebException : The remote server returned an error: (404) Not Found. How can make my test pass? I just need make an assertion that this request with wrong ID will give 404 response from server.


Solution

  • WebException is thrown so you may try to use the Assert.Throws method (may depend from the test API you are using)

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

    the problem is that ProtocolError is not 404 only unfortunately.

    you may try with HttpClient instead

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