Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot assert Bad Request [HTTP 400 error] using RestSharp. Throws System.Net.Http.HttpRequestException

Using RestSharp I have written the following test and the expected outcome is to return error 400 with some error messages in Json format.

But the following test fails at await client.PostAsync(request) and throws "System.Net.Http.HttpRequestException : Request failed with status code BadRequest" and does not reach the Assertion statement.

Using Fiddler I verified my request and Reponses are working as expected.

Would appreciate any advice to solve this. Thank you!

    [Test]
    public async Task Test1Async()
    {
        var jsonData = json;
        var client = new RestClient(endpoint);
        var request = new RestRequest();
        request.AddStringBody(jsonData, ContentType.Json);
        var response = await client.PostAsync(request);
        Assert.AreEqual(400, response.StatusCode);
    }

Solution that worked. Thanks Nicolas VERHELST...

    [Test]
    public async Task Test1Async()
    {
        var jsonData = json;
        var client = new RestClient(endpoint);
        var request = new RestRequest();
        request.AddStringBody(jsonData, ContentType.Json);
        var response = await client.ExecutePostAsync(request);
        Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);
    }
like image 680
UmeshB Avatar asked Jul 21 '26 07:07

UmeshB


1 Answers

If you are worried about the method PostAsync(..) throwing when you get a bad status (e.g. 400), you can use ExecutePostAsync(..) instead.

See the table in here: https://restsharp.dev/error-handling.html

like image 83
Nicolas Avatar answered Jul 22 '26 22:07

Nicolas