Lesson 02 of 93 · 7 min read · Updated

Unit vs Integration vs End-to-End Tests: The Boundary Matters, Not the Framework

Unit tests, integration tests and end-to-end tests are often explained by the tool that runs them. That explanation is wrong. In .NET you can write all three with xUnit. What separates them is the boundary the test crosses. This lesson shows a pricing service that depends on an exchange rate provider, and an integration test that wires two real components together.

Technical Requirements

  1. .NET 11 SDK (projects target net11.0)
  2. xunit 2.9.3
  3. xunit.runner.visualstudio 4.0.1 and Microsoft.NET.Test.Sdk 18.12.0

No Docker and no network are needed. The "real" dependency in this lesson is an in-process implementation, so the tests stay fast while still showing the idea.

Three Kinds of Tests, One Question

Ask one question about each test: what does it connect to?

Test typeWhat it exercisesTypical cost
UnitOne behavior of in-process code. Slow or non-deterministic dependencies are replaced with test doubles.Milliseconds, never flaky
IntegrationTwo or more real components working together, often across a real boundary such as a database or HTTP.Slower, needs setup, more fragile
End-to-endThe whole deployed system, from the user interface or public API down to real storage.Slowest, most fragile, hardest to debug

The cost grows as the test moves outward. Each step adds more moving parts that can fail for reasons unrelated to the code you changed. That is why you write many unit tests, fewer integration tests and only a handful of end-to-end tests.

A Boundary Behind an Interface

In a real shop, an exchange rate comes from an HTTP service. That service is slow, its values change all the time and it does not work offline. In other words, it is not deterministic. So the code hides it behind an interface:

M01.Foundations/Ports/IExchangeRateProvider.cs

namespace M01.Foundations.Ports;

/// <summary>
/// PORT (boundary) interface.
///
/// In real life the exchange rate comes from an HTTP service: it is slow,
/// it changes all the time, and it does not work offline. In other words,
/// it is NOT DETERMINISTIC.
/// That is why we put it behind an interface. This is called a "seam".
///
/// - Unit test: uses a fake (test double) implementation of this interface.
/// - Integration test: uses the real HTTP implementation.
/// </summary>
public interface IExchangeRateProvider
{
/// <summary>How many TL is 1 unit of <paramref name="currency"/> worth?</summary>
Task<decimal> GetTryRateAsync(string currency, CancellationToken cancellationToken = default);
}

A seam is a place where you can change the behavior of a program without editing the code at that place. Here the seam is the constructor parameter of PricingService. Production code passes an HTTP-based provider. A unit test passes a fake. An integration test passes a real implementation.

M01.Foundations/Ports/PricingService.cs

using M01.Foundations.Domain;

namespace M01.Foundations.Ports;

/// <summary>
/// Prices the cart in a foreign currency.
///
/// This class talks to a boundary (IExchangeRateProvider), so its tests
/// must take control of that boundary.
/// </summary>
public sealed class PricingService(IExchangeRateProvider rateProvider)
{
private readonly IExchangeRateProvider _rateProvider =
rateProvider ?? throw new ArgumentNullException(nameof(rateProvider));

/// <summary>Returns the cart total in the given currency.</summary>
public async Task<decimal> TotalInAsync(
Cart cart,
string currency,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(cart);
ArgumentException.ThrowIfNullOrWhiteSpace(currency);

var rate = await _rateProvider.GetTryRateAsync(currency, cancellationToken);

if (rate <= 0)
{
throw new InvalidOperationException($"'{currency}' için geçersiz kur: {rate}");
}

// Passing the CancellationToken down makes cancellation
// behavior testable too.
return decimal.Round(cart.Total() / rate, 2, MidpointRounding.AwayFromZero);
}
}

Why does PricingService take an IExchangeRateProvider instead of creating an HttpClient itself? If it created the client internally, every test of the pricing logic would need a working network and a rate service that returns known values. The interface lets each test decide what sits on the other side of the boundary.

A Second Real Component

For the integration test we need a real implementation of the port. In production this class would wrap an HttpClient. In the sample it reads from a dictionary, which keeps the test in-process:

M01.Foundations/Infrastructure/InMemoryExchangeRateProvider.cs

using M01.Foundations.Ports;

namespace M01.Foundations.Infrastructure;

/// <summary>
/// A simple, realistic but in-process implementation.
/// In a real project, an HttpClient would be here.
///
/// This class exists to show two real components
/// (PricingService + this provider) working together in the integration test.
/// </summary>
public sealed class InMemoryExchangeRateProvider(IReadOnlyDictionary<string, decimal> rates)
: IExchangeRateProvider
{
private readonly IReadOnlyDictionary<string, decimal> _rates = rates;

public Task<decimal> GetTryRateAsync(string currency, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();

return _rates.TryGetValue(currency, out var rate)
? Task.FromResult(rate)
: throw new KeyNotFoundException($"'{currency}' için kur tanımlı değil.");
}
}

The Integration Tests

These tests use the same framework as the unit tests: [Fact], Assert.Equal, Assert.ThrowsAsync. The difference is in the Arrange step. Instead of replacing the dependency, it connects two real components.

M01.Foundations.Tests/Integration/PricingServiceIntegrationTests.cs

using M01.Foundations.Domain;
using M01.Foundations.Infrastructure;
using M01.Foundations.Ports;

namespace M01.Foundations.Tests.Integration;

[Trait("Kapsam", "Integration")]
public class PricingServiceIntegrationTests
{
private static Cart CartWorth2000()
{
var cart = new Cart();
cart.Add(new CartLine("MONITOR-27", 2_000m, 1));
return cart;
}

[Fact]
public async Task TotalInAsync_UsesRateFromProvider()
{
// Arrange: we wire two real components together.
IExchangeRateProvider provider =
new InMemoryExchangeRateProvider(new Dictionary<string, decimal> { ["USD"] = 40m });
var sut = new PricingService(provider);

// Act
var total = await sut.TotalInAsync(CartWorth2000(), "USD");

// Assert: 2000 TL - 10% discount = 1800 TL -> 1800 / 40 = 45 USD
Assert.Equal(45m, total);
}

[Fact]
public async Task TotalInAsync_WhenCurrencyIsUnknown_PropagatesProviderFailure()
{
IExchangeRateProvider provider =
new InMemoryExchangeRateProvider(new Dictionary<string, decimal> { ["USD"] = 40m });
var sut = new PricingService(provider);

// We verify how the boundary's failure flows upward.
await Assert.ThrowsAsync<KeyNotFoundException>(
() => sut.TotalInAsync(CartWorth2000(), "JPY"));
}

[Fact]
public async Task TotalInAsync_WhenRateIsInvalid_ThrowsInvalidOperation()
{
IExchangeRateProvider provider =
new InMemoryExchangeRateProvider(new Dictionary<string, decimal> { ["USD"] = 0m });
var sut = new PricingService(provider);

await Assert.ThrowsAsync<InvalidOperationException>(
() => sut.TotalInAsync(CartWorth2000(), "USD"));
}
}

The first test checks the happy path through both components. The second checks that a failure inside the provider reaches the caller unchanged. The third checks that PricingService guards against a rate of zero, which would otherwise cause a division by zero. Failure behavior across a boundary is one of the main things integration tests are good at finding.

Note that these tests are still in-process. When the provider becomes a real HTTP client or a real database, each test costs more and can fail because of the network or the environment. That cost is why integration tests sit in the middle of the test pyramid, in smaller numbers than unit tests.

Where End-to-End Tests Fit

An end-to-end test of this feature would start the deployed application, add a product to the cart through the API or the browser, and read the converted total from the response. It would use the real rate service and the real database. Such a test gives the most confidence that the system works as a whole, but it is slow, needs a full environment and fails for many reasons at once. Keep these tests for a few critical user journeys.

Summary

  1. The difference between unit, integration and end-to-end tests is the boundary the test crosses, not the framework.
  2. Put slow or non-deterministic dependencies behind an interface; the interface is a seam that tests can control.
  3. Unit tests replace the dependency with a test double; integration tests connect real components.
  4. Integration tests are good at checking how failures flow across a boundary.
  5. Cost and fragility grow as tests move outward, so you need fewer integration and end-to-end tests than unit tests.