Using a custom HttpClient in RestAssured.Net
Last week, I had the pleasure of being a guest on the Test Automation Experience show with Nikolay Advolodkin. In this episode, we talked about RestAssured.Net, I released version 4.1.0 during the podcast, and we discussed some features that have been added to the library in the last couple of releases.
If you want to watch the episode, you can find it on YouTube here.
In this short blog post, I want to highlight the most important new feature of RestAssured.Net version 4.1.0, which is the ability to inject a custom
System.Net.Http.HttpClient (docs) into your tests.
Where is this useful?
By default, RestAssured.Net creates its own
HttpClient to send the requests you create using the fluent syntax that the library provides, for example:
In many situations, the default
HttpClient created by RestAssured.Net is perfectly capable of running the tests you want to perform.
In some cases, however, you either
- are working with a framework that provides and manages its own
HttpClient, most notably Microsoft.AspNetCore.Mvc.Testing, which can be used to write tests for ASP.NET Core APIs
- want to do some custom configuration on the
HttpClientand/or the associated
In those cases, it would be useful to hand-roll an
HttpClient and inject it into your RestAssured.Net tests.
And that’s exactly what you can do starting from RestAssured.Net 4.1.0:
This example contains a test for an ASP.NET Core minimal API, which is contained in the
Program class. To be able to write efficient tests, where the
Microsoft.AspNetCore.Mvc.Testing library handles managing configuring and starting and stopping the API in-memory, you’ll need to use the
HttpClient returned by the
CreateDefaultClient() or the
As you can see, RestAssured now supports this by passing the
HttpClient as an argument to the
Given() method. If an
HttpClient is supplied, RestAssured.Net will use that one, if none is supplied, it will generate its own and use that to send requests and receive responses.
I’m very happy that this feature is now finally available in RestAssured.Net, because I believe that it makes the library much more versatile, and it opens up a lot of new use cases.
As always, I’d love to hear what you think!"