Search⌘ K
AI Features

Solution Review: Mocking an External Service

Explore how to effectively mock external services in .NET unit tests with xUnit and Moq. Understand setting up mock objects, injecting dependencies, configuring method returns, and verifying method calls for isolated and reliable testing outcomes.

We'll cover the following...

The complete solution is presented in the following playground:

using Newtonsoft.Json;
using WebApiApp.Models;

namespace WebApiApp;

public class UserFacade : IUserFacade
{
    private readonly IHttpClientFactory _httpClientFactory;

    public UserFacade(IHttpClientFactory httpClientFactory)
    {
        _httpClientFactory = httpClientFactory;
    }

    public async Task<IEnumerable<User>> GetAll()
    {
        var httpClient = GetHttpClient();
        var response = await httpClient.GetAsync("users");
        var body = await response.Content.ReadAsStringAsync();

        return JsonConvert.DeserializeObject<List<User>>(body);
    }

    private HttpClient GetHttpClient()
    {
        return _httpClientFactory.CreateClient("UsersService");
    }
}
Complete solution with the Moq library

We make the following changes to the UserDataServiceTests.cs file:

  • Line 1: We add a ...