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

前端 未结 4 1056
隐瞒了意图╮
隐瞒了意图╮ 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:37

    I was just looking for the same thing but came up with a more concise approach that didn't use http client. I wanted a test to assert the message handler consumed a mocked logging component. I didn't really need the inner handler to function, just to "stub" it out to satisfy the unit test. Works for my purpose :)

    //ARRANGE
            var logger = new Mock();
            var handler= new ServiceLoggingHandler(logger.Object);
            var request = ControllerContext.CreateHttpRequest(Guid.NewGuid(), "http://test",HttpMethod.Get);
    
            handler.InnerHandler = new Mock(MockBehavior.Loose).Object;
    
            request.Content = new ObjectContent(Company.CreateCompanyDTO(), new JsonMediaTypeFormatter());
            var invoker = new HttpMessageInvoker(handler);
    
            //ACT
            var result = invoker.SendAsync(request, new System.Threading.CancellationToken()).Result;
    
    //ASSERT
    
    

提交回复
热议问题