code4it-dev / blog-comments

https://www.code4it.dev/
1 stars 0 forks source link

blog/testing-httpclientfactory-moq #25

Open utterances-bot opened 2 years ago

utterances-bot commented 2 years ago

How to test HttpClientFactory with Moq - Code4IT

Mocking IHttpClientFactory is hard, but luckily we can use some advanced features of Moq to write better tests.

https://www.code4it.dev/blog/testing-httpclientfactory-moq

CmdrBeavis commented 2 years ago

Was this NOT a thing when you wrote this article?

System.NotSupportedException HResult=0x80131515 Message=Unsupported expression: x => x.CreateClient() Extension methods (here: HttpClientFactoryExtensions.CreateClient) may not be used in setup / verification expressions. Source=Moq

Hopefully I can find something out there on how to fix this. : /

CmdrBeavis commented 2 years ago

The answer is that you must created a "Named" HttpClient via the .CreateClient("this can be empty") method.

bellons91 commented 2 years ago

Yes, if you use named HttpClients, you have to specify the name of the client in the tests.

Otherwise, the solution I shared is fine. You can download and run the tests here.