Modern ASP.NET Core applications often depend on multiple external services to build a single API response. An application might retrieve customer information from one service, order history from another, and payment details from a third service. The API combines these results and returns them to the client.
This approach works well when every dependency is available and returns complete data. However, real applications cannot always depend on that situation. An external service may return incomplete information, a downstream API may fail, or one service may respond successfully while another takes too long.
For example, an order summary API might successfully retrieve customer information and order history but fail to retrieve payment details. Returning an error for the entire request may not always be the best choice. The application might still be able to provide useful information by returning the available results and clearly indicating which section could not be loaded.
This behavior is commonly known as partial data handling.
Testing this type of API requires more than checking successful responses. Developers must verify how the application behaves when individual dependencies return incomplete data, fail independently, or provide unexpected responses.
In this article, we will explore how to test ASP.NET Core APIs when external dependencies return partial data, using HttpClient, dependency injection, and integration testing techniques.
Understanding Partial Data in ASP.NET Core APIs
Consider an API that returns an order summary containing three sections:
- Customer information
- Order history
- Payment information
Each section comes from a separate external service.
When all services respond successfully, the API returns a complete response. However, if the payment service is unavailable, the API may still have enough information to return the customer and order details.
A partial response could look like this:
{
"customer": {
"id": 101,
"name": "John Smith"
},
"orders": [
{
"id": 501,
"total": 250.00
}
],
"payment": null,
"warnings": [
"Payment information is temporarily unavailable."
]
}The response contains useful information even though one dependency failed.
This behavior is useful in dashboards, reporting systems, customer portals, and applications that combine information from multiple services.
However, partial data should be an intentional application behavior. It should not silently hide unexpected failures or make incomplete information appear complete.
Creating Models for the API Response
Start by creating response models for the order summary.
public class CustomerDto
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
}
public class OrderDto
{
public int Id { get; set; }
public decimal Total { get; set; }
}
public class PaymentDto
{
public int PaymentId { get; set; }
public string Status { get; set; } = string.Empty;
}Next, create a response model that combines all three sections.
public class OrderSummaryResponse
{
public CustomerDto? Customer { get; set; }
public List<OrderDto> Orders { get; set; } = [];
public PaymentDto? Payment { get; set; }
public List<string> Warnings { get; set; } = [];
}The nullable Customer and Payment properties allow the application to represent unavailable information.
The Orders property starts as an empty collection so clients do not need to handle a null collection when no order data is available.
For larger applications, it can also be useful to include a status for each section, such as Available, Partial, or Unavailable. This gives clients more information than a null value alone.
Creating External Service Clients
The application needs separate clients for the customer, order, and payment services.
Create a service interface for each dependency.
public interface ICustomerService
{
Task<CustomerDto?> GetCustomerAsync(
int customerId,
CancellationToken cancellationToken);
}
public interface IOrderService
{
Task<List<OrderDto>> GetOrdersAsync(
int customerId,
CancellationToken cancellationToken);
}
public interface IPaymentService
{
Task<PaymentDto?> GetPaymentAsync(
int customerId,
CancellationToken cancellationToken);
}Each implementation can use a typed HttpClient to communicate with its corresponding external API.
For example, the customer service might look like this:
public class CustomerService : ICustomerService
{
private readonly HttpClient _httpClient;
public CustomerService(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<CustomerDto?> GetCustomerAsync(
int customerId,
CancellationToken cancellationToken)
{
return await _httpClient.GetFromJsonAsync<CustomerDto>(
$"/api/customers/{customerId}",
cancellationToken);
}
}The order and payment services can follow the same pattern.
Register the typed clients in Program.cs:
builder.Services.AddHttpClient<ICustomerService, CustomerService>();
builder.Services.AddHttpClient<IOrderService, OrderService>();
builder.Services.AddHttpClient<IPaymentService, PaymentService>();In a real application, configure the base addresses and authentication settings for each external service through configuration.
Handling Partial Failures in the Application
The next step is to create a service that combines the results from all three dependencies.
One important decision is how to handle failures independently. If all three operations are executed using Task.WhenAll and one operation throws an exception, the combined task fails. This can prevent the application from using results that other services successfully returned.
A better approach for this scenario is to handle expected dependency failures separately.
Create a service named OrderSummaryService:
public class OrderSummaryService
{
private readonly ICustomerService _customerService;
private readonly IOrderService _orderService;
private readonly IPaymentService _paymentService;
public OrderSummaryService(
ICustomerService customerService,
IOrderService orderService,
IPaymentService paymentService)
{
_customerService = customerService;
_orderService = orderService;
_paymentService = paymentService;
}
public async Task<OrderSummaryResponse> GetSummaryAsync(
int customerId,
CancellationToken cancellationToken)
{
var response = new OrderSummaryResponse();
var customerTask = LoadCustomerAsync(
customerId, response, cancellationToken);
var ordersTask = LoadOrdersAsync(
customerId, response, cancellationToken);
var paymentTask = LoadPaymentAsync(
customerId, response, cancellationToken);
await Task.WhenAll(
customerTask,
ordersTask,
paymentTask);
return response;
}
private async Task LoadCustomerAsync(
int customerId,
OrderSummaryResponse response,
CancellationToken cancellationToken)
{
try
{
response.Customer =
await _customerService.GetCustomerAsync(
customerId, cancellationToken);
}
catch (HttpRequestException)
{
response.Warnings.Add(
"Customer information is unavailable.");
}
}
private async Task LoadOrdersAsync(
int customerId,
OrderSummaryResponse response,
CancellationToken cancellationToken)
{
try
{
response.Orders =
await _orderService.GetOrdersAsync(
customerId, cancellationToken);
}
catch (HttpRequestException)
{
response.Warnings.Add(
"Order history is unavailable.");
}
}
private async Task LoadPaymentAsync(
int customerId,
OrderSummaryResponse response,
CancellationToken cancellationToken)
{
try
{
response.Payment =
await _paymentService.GetPaymentAsync(
customerId, cancellationToken);
}
catch (HttpRequestException)
{
response.Warnings.Add(
"Payment information is unavailable.");
}
}
}
Join the conversation! Your thoughts help the community grow.