Azure-docs: Testing and the static HttpClient

Created on 30 Aug 2018  Â·  10Comments  Â·  Source: MicrosoftDocs/azure-docs

One issue with using a static HttpClient like this is you have no ability to mock calls to perform unit testing. Perhaps using an injected HttpMessageHandler, which can be mocked, might be a better way to go for the client.


Document Details

⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

assigned-to-author azure-functionsvc functionsvc product-feedback triaged

Most helpful comment

We may want to hold off until we do the DI article that I am working on right now. It will showcase the HttpClientFactory approach

All 10 comments

Thanks for the feedback! We are currently investigating and will update you shortly.

@scottrudy Thank you for your valuable feedback! We have assigned this issue to the author to review further and take the right course of action.

@jeffhollan do you have any feedback on this suggestion from @scottrudy?

We do plan to provide better HTTP injection in the future (sometime early next year most likely). That said putting in your own HttpMessageHandler is a viable option for now as shown in this sample. Likely would wrap up in a better DI article that hopefully will come by end of the year.

For HttpClient, wouldn't it be a good approach to keep the HttpClientFactory as a static member and create HttpClient by using CreateClient factory method? this way, we are delegating the HttpClient creation responsibility to the factory which knows how to deal with the HttpClient effectively.

@craigshoemaker is this something you think we should address in the testing article?

We may want to hold off until we do the DI article that I am working on right now. It will showcase the HttpClientFactory approach

@mike-urnun-msft can you also please change the service label to azure-functions/svc? Thanks!

Hi @scottrudy and @jeffhollan,

Good day to you.

We can add httpclient through DI using http extensions thus we can create mock object of it for testing, refer below reference that may help you.

https://stackoverflow.com/questions/52918000/ihttpclientfactory-in-net-core-2-1-console-app-references-system-net-http
https://dotnetcoretutorials.com/2018/05/03/httpclient-factories-in-net-core-2-1/

Thanks!

The new dependency injection article also now features HttpClient injection.

please-close

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Ponant picture Ponant  Â·  3Comments

Agazoth picture Agazoth  Â·  3Comments

jamesgallagher-ie picture jamesgallagher-ie  Â·  3Comments

ianpowell2017 picture ianpowell2017  Â·  3Comments

JeffLoo-ong picture JeffLoo-ong  Â·  3Comments