Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using HttpClientTest.Class;
using Moq;
using Xunit;
namespace HttpClientTest.Tests
{
public class InternetCallerTests
{
[Fact]
public async Task GivenAConfiguredHttpClient_WhenCallingAUrlAndTheResultIsTheExpectedResult_ThenTrueIsReturned()
{
// Arrange
var httpClient = new HttpClient(new OkMessageHandler());
var factoryMock = new Mock<IHttpClientFactory>();
ICallTheInternet subject = new InternetCaller(factoryMock.Object);
// Act
var result = await subject.GetWithClient(httpClient, "https://example.com", HttpStatusCode.OK);
// Assert
result.Should().BeTrue();
}
[Fact]
public async Task GivenAHttpClientFactoryConfiguredWithNamedHttpClient_WhenCallingAUrlAndTheResultIsTheExpectedResult_ThenTrueIsReturned()
{
// Arrange
var httpClient = new HttpClient(new OkMessageHandler());
var factoryMock = new Mock<IHttpClientFactory>();
ICallTheInternet subject = new InternetCaller(factoryMock.Object);
var clientName = "TestClient";
factoryMock.Setup(f => f.CreateClient(clientName)).Returns(httpClient);
// Act
var result = await subject.GetWithNamedClient(clientName, "https://example.com", HttpStatusCode.OK);
// Assert
result.Should().BeTrue();
}
internal class OkMessageHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment