How to mock the new HttpClientFactory in .NET Core 2.1 using Moq

前端 未结 3 1989
梦如初夏
梦如初夏 2020-11-28 11:12

.NET Core 2.1 comes with this new factory called HttpClientFactory, but I can\'t figure out how to mock it to unit test some methods that include REST service c

3条回答
  •  萌比男神i
    2020-11-28 11:58

    In addition to the previous post that describes how to setup a stub, you can just use Moq to setup the DelegatingHandler:

    var clientHandlerMock = new Mock();
    clientHandlerMock.Protected()
        .Setup>("SendAsync", ItExpr.IsAny(), ItExpr.IsAny())
        .ReturnsAsync(new HttpResponseMessage(HttpStatusCode.OK))
        .Verifiable();
    clientHandlerMock.As().Setup(s => s.Dispose());
    
    var httpClient = new HttpClient(clientHandlerMock.Object);
    
    var clientFactoryMock = new Mock(MockBehavior.Strict);
    clientFactoryMock.Setup(cf => cf.CreateClient()).Returns(httpClient).Verifiable();
    
    clientFactoryMock.Verify(cf => cf.CreateClient());
    clientHandlerMock.Protected().Verify("SendAsync", Times.Exactly(1), ItExpr.IsAny(), ItExpr.IsAny());
    

提交回复
热议问题