Solution Review: Improving Code Coverage Metrics
Explore how to improve code coverage metrics by adding integration tests in the ApiTests.cs file. Learn to use WebApplicationFactory, HttpClient, and validate GET endpoints. Understand how these tests execute real application code and increase coverage through practical verification of controller methods.
We'll cover the following...
We'll cover the following...
The following playground contains the complete solution to the challenge:
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using WebApiApp.Models;
using static System.Runtime.InteropServices.JavaScript.JSType;
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);
}
public async Task<bool> AddUser(User user)
{
var httpClient = GetHttpClient();
var content = new StringContent(JsonConvert.SerializeObject(user));
var response = await httpClient.PostAsync("users", content);
return response.IsSuccessStatusCode;
}
private HttpClient GetHttpClient()
{
return _httpClientFactory.CreateClient("UsersService");
}
}Final setup with additional code coverage
To solve the challenge, we add some integration tests to the ApiTests.cs file. Here is the full list of changes we applied:
...