2

We are using FlurlClient in a few projects and familiar with their fluent interface. We now want to use it in asp.net core integration tests using TestServer. The example from http://asp.net-hacker.rocks/2017/09/27/testing-aspnetcore.html

_server = new TestServer(new WebHostBuilder()
                             .UseStartup<Startup>());
_client = _server.CreateClient();

I was going to change code to

_server = new TestServer(new WebHostBuilder()
                             .UseStartup<Startup>());
var httpClient = _server.CreateClient();
_client = new FlurlClient(httpClient);

and use all FlurlClient methods/extensions.

But then I noticed Is it possible to use Furl.Http with the OWIN TestServer? which described that more work is required in owin implementation.

Is approach for Asp.Net Core TestServer similar? Or is it simplified?

Todd Menier
  • 37,557
  • 17
  • 150
  • 173
Michael Freidgeim
  • 26,542
  • 16
  • 152
  • 170

1 Answers1

6

It's much simplified, and your proposed change is exactly right. The question you linked to is old and my answer contains information that's no longer relevant in 2.x. (I have updated it.) In fact, the ability to provide an existing HttpClient directly in a FlurlClient constructor was added very recently, and with this specific use case in mind.

Here's an extension method I use as a replacement for CreateClient; you might find it handy if you do this a lot:

public static class TestServerExtensions
{
    public static IFlurlClient CreateFlurlClient(this TestServer server) => 
        new FlurlClient(server.CreateClient());
}
Todd Menier
  • 37,557
  • 17
  • 150
  • 173
  • Hi @todd-menier One Question: In my specific scenario I need to add a HttpClientHandler to testservers CreateClient-Method to be able to make calls via SSL with a self-signed certificate in an integration test (using testcontainers and having a keycloak spin up in docker and want to get validate a token when calling my apps API, this fails atm because the cert is not valid). As far as I found out, it is not possible with Testserver itself. So would it be possible when I wrap the HttpClient into a FlurlClient? – Dominik Feb 04 '21 at 10:08
  • 1
    @Dominik No, if it can't be done with TestServer/HttpClient, then wrapping it with Flurl won't help. Flurl just puts a prettier face on HttpClient but still defers the bulk of the actual work to it. – Todd Menier Feb 05 '21 at 13:30
  • Thanks for clarification, I thought so. So i added this question and hoping for better luck there: https://stackoverflow.com/questions/66062832/calling-thirdparty-container-with-net-core-testhost-testserver-via-ssl-bypass :) – Dominik Feb 05 '21 at 14:47