Search
 
SCRIPT & CODE EXAMPLE
 

CSHARP

how to mock http client c#

//To really understand please read source blog
//https://gingter.org/2018/07/26/how-to-mock-httpclient-in-your-net-c-unit-tests/
	
// ARRANGE
var handlerMock = new Mock<HttpMessageHandler>(MockBehavior.Strict);
handlerMock
   .Protected()
   // Setup the PROTECTED method to mock
   .Setup<Task<HttpResponseMessage>>(
      "SendAsync",
      ItExpr.IsAny<HttpRequestMessage>(),
      ItExpr.IsAny<CancellationToken>()
   )
   // prepare the expected response of the mocked http call
   .ReturnsAsync(new HttpResponseMessage()
   {
      StatusCode = HttpStatusCode.OK,
      Content = new StringContent("[{'id':1,'value':'1'}]"),
   })
   .Verifiable();
 
// use real http client with mocked handler here
var httpClient = new HttpClient(handlerMock.Object)
{
   BaseAddress = new Uri("http://test.com/"),
};
 
var subjectUnderTest = new MyTestClass(httpClient);
 
// ACT
var result = await subjectUnderTest
   .GetSomethingRemoteAsync('api/test/whatever');
 
// ASSERT
result.Should().NotBeNull(); // this is fluent assertions here...
result.Id.Should().Be(1);
 
// also check the 'http' call was like we expected it
var expectedUri = new Uri("http://test.com/api/test/whatever");
 
handlerMock.Protected().Verify(
   "SendAsync",
   Times.Exactly(1), // we expected a single external request
   ItExpr.Is<HttpRequestMessage>(req =>
      req.Method == HttpMethod.Get  // we expected a GET request
      && req.RequestUri == expectedUri // to this uri
   ),
   ItExpr.IsAny<CancellationToken>()
);
Comment

PREVIOUS NEXT
Code Example
Csharp :: how to populate list in c# 
Csharp :: rotation 
Csharp :: list of function in c# 
Csharp :: c# get smallest of 3 numbers 
Csharp :: c# compare dateTime with string 
Csharp :: sieve 
Csharp :: C# System.nanoTime 
Csharp :: .net json result status code not working 
Csharp :: how to change text in richtextbox wpf 
Csharp :: c# convertir caracter con tilde 
Csharp :: go right unity 
Csharp :: How do I allow edit only a particular column in datagridview in windows application 
Csharp :: c# chance of 
Csharp :: Options Pattern startup.cs configuration 
Csharp :: Rotating an object in Unity usign Physics 
Csharp :: c# external ip 
Csharp :: blazor clientside cookies 
Csharp :: how to know pm or am C# 
Csharp :: c# check port in remote pc 
Csharp :: encrypt password easiest way in web app .net 
Csharp :: c# draggable controls 
Csharp :: c# mock ref parameter 
Csharp :: httpclient getstringasync 
Csharp :: generate a dropdown list from array data using razor .net mvc 
Csharp :: c# reflection get property value array 
Csharp :: c# slice array 
Csharp :: how to get properties from json in c# 
Csharp :: strinng.indexOf c# 
Csharp :: delete items in c# 
Csharp :: c# how to initialize an array 
ADD CONTENT
Topic
Content
Source link
Name
3+7 =