Lesson 76 of 93 · 5 min read · Updated

Unit or Integration? Drawing the Boundary Between Test Types in .NET

Teams often argue about whether a test is "really" a unit test or an integration test. The label matters less than the decision behind it: which boundary does this test need to cross to catch the risk you care about? This lesson gives a simple rule for that decision and applies it to real tests from a Books API, so you can see the same feature tested at two different levels.

Technical Requirements

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. Microsoft.AspNetCore.Mvc.Testing 11.0.0
  4. Microsoft.EntityFrameworkCore.Sqlite 11.0.0
  5. Microsoft.Extensions.TimeProvider.Testing 11.0.0
  6. FluentAssertions 7.2.2
  7. Docker is not required.

The Rule: What Are You Testing?

Classify a test by what it exercises, not by the tool it uses.

If I am testing…Test type
Pure in-process logicUnit
A real EF Core provider, the file system, an HTTP host, a message brokerIntegration

Then apply one guideline: choose the smallest boundary that can expose the risk. A bigger boundary is not a better test. It is slower, it has more reasons to fail, and when it fails it points less clearly at the cause. A smaller boundary that cannot see the risk is not a better test either. It is a green test that proves nothing.

Same Feature, Two Levels

The Books API has a background job that deletes expired reservations. The deletion logic lives in ExpiredReservationCleaner. Its rule is simple: a reservation whose ExpiresAtUtc is less than or equal to "now" is expired.

M09.IntegrationApi/Background/ReservationCleanup.cs

public sealed class ExpiredReservationCleaner(AppDbContext db, TimeProvider timeProvider) : IReservationCleaner
{
public Task<int> CleanAsync(CancellationToken cancellationToken)
{
var now = timeProvider.GetUtcNow();

// Boundary rule: a reservation with ExpiresAtUtc == now is also EXPIRED.
return db.Reservations
.Where(r => r.ExpiresAtUtc <= now)
.ExecuteDeleteAsync(cancellationToken);
}
}

The boundary rule (== now counts as expired) is business logic. A test for it does not need an HTTP host. It needs a database that can run ExecuteDeleteAsync, because the EF InMemory provider does not support bulk deletes, and a fake clock. So the test creates the cleaner directly, with SQLite in-memory and a FakeTimeProvider:

M09.IntegrationApi.Tests/BackgroundServiceUnitTests.cs

[Fact]
public async Task CleanAsync_ReservationExpiringExactlyNow_IsRemoved()
{
// Arrange — BOUNDARY: the reservation expires "exactly now".
await using var db = CreateDb();
db.Reservations.Add(Reservation("sinir@ornek.com", expiresAt: Start.AddMinutes(10)));
await db.SaveChangesAsync();

var cleaner = new ExpiredReservationCleaner(db, _clock);

// Act — move the clock exactly to the boundary; with a real clock this test is close to impossible.
_clock.Advance(TimeSpan.FromMinutes(10));
var removed = await cleaner.CleanAsync(CancellationToken.None);

// Assert
removed.Should().Be(1);
}

This is a narrow test. No routing, no DI container, no hosted service. When it fails, the cause is in one method.

The question "is the job wired into the real application?" is different. That question involves Program.cs, the DI container, scopes and the hosted service lifecycle. No narrow test can answer it. The host-level test in BackgroundServiceIntegrationTests answers it by starting the real application through BooksApiFactory. A later lesson covers both tests in detail. The point here is that each test has one job, and each uses the smallest boundary that can do that job.

A Test That Can Only Be an Integration Test

Some risks live entirely in the wiring. Look at how the delete endpoint is mapped:

M09.IntegrationApi/Endpoints/BookEndpoints.cs

// Protected endpoint: the integration test reaches it
// through the test authentication scheme.
books.MapDelete("/{id:int}", DeleteAsync).RequireAuthorization("AdminOnly");

Could the "anonymous user gets 401" rule be tested with a unit test? You could call DeleteAsync directly, but the method has no authorization logic inside it. The rule is a piece of endpoint metadata that the authorization middleware reads at runtime. A unit test of the method would pass even if RequireAuthorization were deleted. The only honest test sends a request through the pipeline:

M09.IntegrationApi.Tests/HttpPipelineTests.cs

[Fact]
public async Task DeleteBook_WithoutAuthentication_Returns401()
{
// The REAL authorization middleware runs — a unit test could not show this.
var response = await _client.DeleteAsync("/api/books/1");

response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
}

The same is true for the 400 response with problem details, the 201 status with a Location header, and the 409 response for a duplicate ISBN. These are behaviours of the endpoint as the client sees it, so the test must stand where the client stands.

Common Mistake: Testing Logic Through the Widest Door

The opposite mistake is common too. If the only tests for the reservation boundary rule went through HTTP, each case would need a host, a seeded database, a clock advance and a status probe. You would write fewer cases because each one is expensive, and the boundary value (== now) would likely be the case you skip.

A practical split for most web APIs:

  1. Business rules and calculations: unit tests, many cases, fast.
  2. Queries and constraints that depend on the database: integration tests against a relational provider.
  3. Routing, authorization, serialization, status codes: integration tests through WebApplicationFactory.
  4. A few critical user journeys: end-to-end tests in a real browser.

Each layer proves something the layer below cannot. None of them replaces the others.

Summary

  1. Classify a test by what it exercises: pure logic is unit, a real provider or host is integration.
  2. Choose the smallest boundary that can expose the risk you care about.
  3. Wiring rules such as RequireAuthorization can only be proven by a request through the real pipeline.
  4. Business rules with many edge cases belong in narrow, fast tests, not behind HTTP.
  5. The same feature often needs tests at two levels: one for the logic and one for the wiring.