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.");
}
}
}Each dependency is loaded independently. If one service throws an HttpRequestException, the application records a warning and continues processing the other results.
Because the three methods update separate properties, they can run concurrently without modifying the same response property.
This example handles expected HTTP communication failures. In production, applications should also consider HTTP error responses, invalid JSON, timeouts, and unexpected responses according to their service contracts.
Do not catch every exception and convert it into missing data. Programming errors and unexpected failures should remain visible through appropriate logging and error handling.
Also, cancellation requested by the incoming client should not be treated as an ordinary dependency failure. OperationCanceledException should normally propagate when the request cancellation token has been canceled.
Creating an Integration Test With Mocked Dependencies
Testing every external service through a real network connection can make integration tests slow and unreliable.
A practical alternative is to use WebApplicationFactory and replace the external service registrations with test implementations.
For example, create a fake payment service that simulates an unavailable dependency.
public class FakePaymentService : IPaymentService
{
public Task<PaymentDto?> GetPaymentAsync(
int customerId,
CancellationToken cancellationToken)
{
throw new HttpRequestException(
"Payment service is unavailable.");
}
}The customer and order services can return valid data.
public class FakeCustomerService : ICustomerService
{
public Task<CustomerDto?> GetCustomerAsync(
int customerId,
CancellationToken cancellationToken)
{
return Task.FromResult<CustomerDto?>(
new CustomerDto
{
Id = customerId,
Name = "John Smith"
});
}
}
public class FakeOrderService : IOrderService
{
public Task<List<OrderDto>> GetOrdersAsync(
int customerId,
CancellationToken cancellationToken)
{
return Task.FromResult(
new List<OrderDto>
{
new OrderDto
{
Id = 501,
Total = 250
}
});
}
}These fake implementations allow the test to control exactly which dependency succeeds and which one fails.
Writing the ASP.NET Core Integration Test
Create a custom WebApplicationFactory and replace the production dependency registrations.
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
public class OrderSummaryFactory
: WebApplicationFactory<Program>
{
protected override void ConfigureWebHost(
IWebHostBuilder builder)
{
builder.ConfigureServices(services =>
{
services.RemoveAll<ICustomerService>();
services.RemoveAll<IOrderService>();
services.RemoveAll<IPaymentService>();
services.AddScoped<ICustomerService, FakeCustomerService>();
services.AddScoped<IOrderService, FakeOrderService>();
services.AddScoped<IPaymentService, FakePaymentService>();
});
}
}The factory removes the original service registrations and adds the fake implementations.
Now write an integration test that sends a request to the order summary endpoint.
using System.Net;
using System.Net.Http.Json;
using Xunit;
public class OrderSummaryTests
: IClassFixture<OrderSummaryFactory>
{
private readonly HttpClient _client;
public OrderSummaryTests(OrderSummaryFactory factory)
{
_client = factory.CreateClient();
}
[Fact]
public async Task GetSummary_ShouldReturnAvailableData()
{
var response = await _client.GetAsync(
"/api/orders/101/summary");
Assert.Equal(
HttpStatusCode.OK,
response.StatusCode);
var result =
await response.Content.ReadFromJsonAsync
<OrderSummaryResponse>();
Assert.NotNull(result);
Assert.Equal(
"John Smith",
result.Customer?.Name);
Assert.Single(result.Orders);
Assert.Null(result.Payment);
Assert.Contains(
result.Warnings,
warning => warning.Contains("Payment"));
}
}This test verifies that the API returns a successful response even though the payment service fails.
It also checks that customer information and order history remain available and that the response contains a warning about the unavailable payment information.
The test assumes that the application exposes the corresponding endpoint and registers OrderSummaryService. It should be connected to the actual API route in the application.
Testing Different Partial Data Scenarios
Testing only one failing dependency is not enough for an API that combines multiple services.
Create additional test cases for different combinations of dependency responses.
Scenario | Expected behavior |
|---|---|
All dependencies succeed | Return complete data |
Customer service fails | Return orders and payment information |
Order service fails | Return customer and payment information |
Payment service fails | Return customer and orders |
All dependencies fail | Return an appropriate error or documented empty response |
A dependency returns no data | Handle the missing result according to the service contract |
For example, a customer service might return null because the customer does not exist. This is different from an HTTP communication failure.
The application should decide whether that situation means the entire request is invalid or whether other sections can still be returned.
Similarly, an external service returning HTTP 200 with an empty collection should not automatically be treated as a service failure. The meaning depends on the API contract.
Best Practices for Testing Partial Responses
Keep each external dependency independently replaceable. This makes it easier to test different failure combinations without starting multiple external services.
Test both successful and unsuccessful HTTP responses. An external service can return HTTP 500, HTTP 404, an empty response, or invalid JSON. These situations may require different handling.
Use cancellation tokens throughout the application. If the client disconnects or cancels the request, the application should stop unnecessary downstream operations where possible.
Add logging for failed dependencies. A partial response may be successful from the API client's perspective, but developers still need to know that a dependency failed.
Avoid returning sensitive exception details to clients. Warning messages should explain which information is unavailable without exposing internal URLs, credentials, database details, or stack traces.
Finally, do not make every dependency failure invisible. Some data may be essential to the business operation. For example, a payment confirmation API should not report success simply because customer information was retrieved successfully.
Summary
ASP.NET Core APIs that combine multiple external services must be prepared for incomplete responses and independent dependency failures. If one service becomes unavailable, the application may still be able to return useful information from the remaining services.
Using dependency interfaces and WebApplicationFactory makes it possible to test these scenarios without relying on real external systems. Developers can replace individual services with controlled test implementations and verify that the API returns the expected data and warnings.
The most important part is to define clear rules for partial responses. Decide which information is optional, which failures should produce warnings, and which failures must stop the entire operation.
With these rules covered by integration tests, applications become more predictable when external dependencies do not behave as expected.

Join the conversation! Your thoughts help the community grow.