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

前端 未结 4 1049
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  萌比男神i
    2020-12-24 06:29

    I also found this answer because i have my custom handler and i want to test it We are using NUnit and Moq, so i think my solution can be helpful for someone

        using Moq;
        using Moq.Protected;
        using NUnit.Framework;
    namespace Unit.Tests
    {
        [TestFixture]
        public sealed class Tests1
        {
            private HttpClient _client;
            private HttpRequestMessage _httpRequest;
            private Mock _testHandler;
    
            private MyCustomHandler _subject;//MyCustomHandler inherits DelegatingHandler
    
            [SetUp]
            public void Setup()
            {
                _httpRequest = new HttpRequestMessage(HttpMethod.Get, "/someurl");
                _testHandler = new Mock();
    
                _subject = new MyCustomHandler // create subject
                {
                    InnerHandler = _testHandler.Object //initialize InnerHandler with our mock
                };
    
                _client = new HttpClient(_subject)
                {
                    BaseAddress = new Uri("http://localhost")
                };
            }
    
            [Test]
            public async Task Given_1()
            {
                var mockedResult = new HttpResponseMessage(HttpStatusCode.Accepted);
    
                void AssertThatRequestCorrect(HttpRequestMessage request, CancellationToken token)
                {
                    Assert.That(request, Is.SameAs(_httpRequest));
                    //... Other asserts
                }
    
                // setup protected SendAsync 
                // our MyCustomHandler will call SendAsync internally, and we want to check this call
                _testHandler
                    .Protected()
                    .Setup>("SendAsync", _httpRequest, ItExpr.IsAny())
                    .Callback(
                        (Action)AssertThatRequestCorrect)
                    .ReturnsAsync(mockedResult);
    
                //Act
                var actualResponse = await _client.SendAsync(_httpRequest);
    
                //check that internal call to SendAsync was only Once and with proper request object
                _testHandler
                    .Protected()
                    .Verify("SendAsync", Times.Once(), _httpRequest, ItExpr.IsAny());
    
                // if our custom handler modifies somehow our response we can check it here
                Assert.That(actualResponse.IsSuccessStatusCode, Is.True);
                Assert.That(actualResponse, Is.EqualTo(mockedResult));
                //...Other asserts
            }
        }
    } 
    

提交回复
热议问题