CodexBloom - Programming Q&A Platform

Difficulty Testing a Method with an External API Call in ASP.NET Core Using Moq

šŸ‘€ Views: 0 šŸ’¬ Answers: 1 šŸ“… Created: 2025-06-14
unit-testing mocks httpclient dotnet6 moq C#

I'm sure I'm missing something obvious here, but I'm stuck trying to I've spent hours debugging this and I'm relatively new to this, so bear with me. I'm trying to write unit tests for a service method that makes an external API call using HttpClient. Here's the method I'm trying to test: ```csharp public class WeatherService { private readonly HttpClient _httpClient; public WeatherService(HttpClient httpClient) { _httpClient = httpClient; } public async Task<string> GetWeatherAsync(string city) { var response = await _httpClient.GetAsync($"api/weather/{city}"); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); } } ``` I'm using Moq to create a mock HttpClient, but I'm running into issues when trying to set up the expected behavior for the GetAsync method. My test code looks like this: ```csharp [Fact] public async Task GetWeatherAsync_ReturnsWeatherData() { var mockHttpMessageHandler = new Mock<HttpMessageHandler>(); mockHttpMessageHandler .Protected() .Setup<Task<HttpResponseMessage>>( "SendAsync", It.IsAny<HttpRequestMessage>(), It.IsAny<CancellationToken>() ) .ReturnsAsync(new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent("{ \"temperature\": 20 }") }); var httpClient = new HttpClient(mockHttpMessageHandler.Object); var service = new WeatherService(httpClient); var result = await service.GetWeatherAsync("London"); Assert.Equal("{ \"temperature\": 20 }", result); } ``` However, when I run the test, I'm getting a `NullReferenceException` on the line where I call `response.EnsureSuccessStatusCode()`. It seems like the mock isn't set up correctly. I've tried to debug and ensure that the mock setup is configured before the service method is called, and I also verified that the city name is correctly passed to the method, but I still need to get it to work. Does anyone have any insights on how to properly mock HttpClient for this kind of scenario? I’m using .NET 6.0 and Moq 4.16.1. What am I doing wrong? I'm working with C# in a Docker container on Ubuntu 20.04. My team is using C# for this mobile app. I'm using C# 3.11 in this project. Any ideas how to fix this?