How can I test a custom DelegatingHandler in the ASP.NET MVC 4 Web API?

前端 未结 4 1063
隐瞒了意图╮
隐瞒了意图╮ 2020-12-24 06:00

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

4条回答
  •  余生分开走
    2020-12-24 06:25

    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);
            }
        }
    

提交回复
热议问题