I\'ve seen this question come up in a few places, and not seen any great answers. As I\'ve had to do this myself a few times, I thought I\'d post my solution. If you have an
I created the following for testing DelegatingHandlers. It is useful for handlers that use the HttpRequestMessage.DependencyScope to resolve dependencies using your favorite IoC framework e.g. a WindsorDependencyResolver with a WindsorContainer:
public class UnitTestHttpMessageInvoker : HttpMessageInvoker
{
private readonly HttpConfiguration configuration;
public UnitTestHttpMessageInvoker(HttpMessageHandler handler, IDependencyResolver resolver)
: base(handler, true)
{
this.configuration = new HttpConfiguration();
configuration.DependencyResolver = resolver;
}
[DebuggerNonUserCode]
public override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
request.Properties["MS_HttpConfiguration"] = this.configuration;
return base.SendAsync(request, cancellationToken);
}
}