Attention when working with the Asp.Net Core TestHost and its HttpMessageHandler

Georg Dangl by Georg Dangl in Web Development Tuesday, November 21, 2017

Tuesday, November 21, 2017

Posted in DotNet Testing

I'm a big fan of the Asp.Net Core TestHost package, which allows you to easily write integration tests of your applications without the need to do actual network calls.

TestServers feature a nice method CreateClient() that returns an HttpClient instance which will interface with the TestServer but not make any actual network calls. So basically, to perform an integration test against one of your endpoints, you treat the client as you would treat a regular one. This can also be used where you have dependencies in your code that themselves need to call your server, for example a Json Web Token authority validation utility.

For these cases, you can supply your own HttpMessageHandler:

Did you spot the error?

Yeah, i actually made the handler to delegate it's call to a new HttpClient. This means a request travels like this: HttpClient -> IntegrationTestsHttpMessageHandler -> HttpClient. If you're familiar with how request are handled internally, you've noticed that the first HttpClient marks the request as sent and the second one then refuses to send the message again with a nice System.InvalidOperationException: Cannot send the same request message multiple times. Luckily, the TestServer has direct access to a HttpMessageHandler:

I've spent the better part of an evening figuring this out...

Happy testing!

Share this post

comments powered by Disqus

About me

Hi, my name's George! I love coding and blogging about it. I focus on all things around .Net, Web Development and DevOps.


Need a consultant for BIM, GAEB or Software Development?

Contact me at [email protected], +49 (173) 56 45 689 or visit my professional page!

// Just 💗 Coding

Social Links