- 
      
 - 
        
Save reyou/5a038bb2b219088264bec7180f8b944e to your computer and use it in GitHub Desktop.  
    Mock an Asp.Net Core HttpClient with a custom HttpMessageHandler using Moq
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | using System; | |
| using System.Net.Http; | |
| using System.Threading; | |
| using System.Threading.Tasks; | |
| using Moq; | |
| using Moq.Protected; | |
| namespace Tests | |
| { | |
| public class MockHttpClient | |
| { | |
| public HttpClient GetMockClient() | |
| { | |
| var mockHttpMessageHandler = new Mock<HttpMessageHandler>(); | |
| mockHttpMessageHandler.Protected() | |
| .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>()) | |
| .Returns((HttpRequestMessage request, CancellationToken cancellationToken) => GetMockResponse(request, cancellationToken)); | |
| return new HttpClient(mockHttpMessageHandler.Object); | |
| } | |
| private Task<HttpResponseMessage> GetMockResponse(HttpRequestMessage request, CancellationToken cancellationToken) | |
| { | |
| if (request.RequestUri.LocalPath == "/expectedPath") | |
| { | |
| var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK); | |
| response.Content = new StringContent(GetAuthJson(), Encoding.UTF8, "application/json"); | |
| return Task.FromResult(response); | |
| } | |
| throw new NotImplementedException(); | |
| } | |
| private string GetAuthJson() | |
| { | |
| return "{ \"isAuthenticated\": true }"; | |
| } | |
| } | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment