.NET, C#, CSharp, Library, Programming

Flurl.Http – HTTP unit testable client for .NET

So far the first choice of many people was RestSharp. Since few months new player is getting a piece of market – Flurl. In this post I would like to introduce this library, show how to use with .NET Core 2.0 and unit test the code.

Code!

Let’s start coding part with getting it – the library is available as Nuget package. There are 2 versions: Flurl and Flurl.Http. Flurl package is just an URL builder, without HTTP features, so it is not enough for us.

From developer perspective, Flurl.Http is a set of extenstion methods which we can invoke on string (url to our resource). Below sample show the easiest, generic method to get the data in JSON.

public async Task<T> GetDataUsingFlur<T>(string url)
{
    return await url.GetJsonAsync<T>();
}

Here is the result for sample request from HackerNews (HNAPI – unofficial API).

 

As you can see, the usage of this library is very friendly and as it is shown in further part really simple.

How to test?

Unfortunately testing documentation is outdated (signature of the method in HttpTest class which is required to unit test your code).

According to documentation current fake setup looks like below:

    httpTest.RespondWith(200, "OK");

However the signatures of the methods says (Flurl.Http version 2.3.1):

    httpTest.RespondWith(string body, [int status = 200], [object headers = null], [object cookies = null]);
    httpTest.RespondWith([HttpContent content = null], [int status = 200], [object headers = null], [object cookies = null]);

So the full test example:

[Test]
public async Task GetDataUsingFlurlSampleRequestsCallsApi()
{
    var sut = new Client();        
    using (var httpTest = new HttpTest())
    {
        // arrange
        httpTest.RespondWith("{\"id\":17408942,\"title\":\"What I Learned Making My Own JIT Language\", \"url\":\"http://www.mikedrivendevelopment.com/2018/06/what-i-learned-making-my-own-jit.html\"}");

        // act
        await sut.GetDataUsingFlurl&lt;HackerNewsEntity&gt;("http://anyaddress");

        // assert
        httpTest.ShouldHaveCalled("http://anyaddress").WithVerb(HttpMethod.Get);
    }
}

All code presented above can be found in this repo – .NET Core 2.0, NUnit.

License

Current version is licensed under MIT license. For current license visit this site.

Support

The approach to support is similar to RestSharp – they are using StackOverlow as support channel. Big plus for being open on community.

Flurl.Http vs RestSharp

Libhunt.com has quite interesting comparison (in terms of code quality) between Flurl.Http and RestSharp. You can find it here.

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *