Unit test code from xUnit

HTTP Client Factory (IHttpClientFactory) mock using NSubstitute

Following the controversy around Moq, I decided to look into using NSubstitute as an alternative mocking library.

The example below is an NSubstitute version of the class created as part of my C# TDD blog article. The only change in functionality is the optional passing in of an HTTP status code.

public static IHttpClientFactory GetStringClient(string returnValue, HttpStatusCode returnStatusCode = HttpStatusCode.OK)
{
	var httpMessageHandler = Substitute.For<HttpMessageHandler>();
	var httpClientFactory = Substitute.For<IHttpClientFactory>();

	httpMessageHandler
		.GetType()
		.GetMethod("SendAsync", BindingFlags.NonPublic | BindingFlags.Instance)
		.Invoke(httpMessageHandler, new object[] { Arg.Any<HttpRequestMessage>(), Arg.Any<CancellationToken>() })
		.Returns(Task.FromResult(new HttpResponseMessage(returnStatusCode) { Content = new StringContent(returnValue) }));

	HttpClient httpClient = new(httpMessageHandler);
	httpClientFactory.CreateClient(Arg.Any<string>()).Returns(httpClient);

	return httpClientFactory;
}

Company Reviews

Leave a Reply