Successfully added
.NET
by Patrik
How to Test a Custom DelegatingHandler in .NET
What’s the Problem?
When writing unit tests for a custom DelegatingHandler
, you might try calling:
var response = await handler.SendAsync(request, cancellationToken);
But this will cause a compiler error. Why? Because SendAsync
in DelegatingHandler
is protected, meaning you can't call it directly from your test project.
The Simple Solution
Use HttpMessageInvoker
, which is designed to work with any HttpMessageHandler
(including DelegatingHandler
). It provides a public SendAsync
method, so you can easily test your handler:
var handler = new YourCustomHandler
{
InnerHandler = new DummyHandler() // Replace with mock/stub as needed
};
var invoker = new HttpMessageInvoker(handler);
var response = await invoker.SendAsync(request, cancellationToken);
This allows you to simulate HTTP requests through your custom handler, without using HttpClient
.
Why This Works
DelegatingHandler
is a subclass ofHttpMessageHandler
.HttpMessageInvoker
takes anyHttpMessageHandler
and exposes a public way to send HTTP requests.- This bypasses the visibility issue with
protected SendAsync
.
Tip for Better Testing
Use a mock InnerHandler
to control the behavior of the response. This helps you test how your DelegatingHandler
reacts to different scenarios.
.NET
unit-testing
httpclient
middleware
csharp
Referenced in:
Comments