Search code examples
c#restsharpweb-api-testing

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

Solution

  • 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