LESSON 15 OF 16

15. Testing, Logging, Documentation, and Production Readiness

This lesson applies unit and integration testing, structured logging, OpenAPI documentation, environment configuration, and basic performance checks to the three-tier .NET application.

75 dk 74

Introduction

An application working on a developer's machine is not automatically ready for production. A real project must prove that expected behavior is preserved, provide useful diagnostic information, document its HTTP contract, and separate development, testing, staging, and production settings safely. In this lesson, we apply these practices to the three-tier solution built throughout the course.

Assume that the solution contains Catalog.Domain, Catalog.Application, Catalog.Infrastructure, Catalog.Api, and Catalog.Tests projects. The example feature manages products through an API. We will test business rules with fast unit tests, verify collaboration between layers with integration tests, add structured logs, expose an OpenAPI description, configure environments, and perform a basic performance observation.

1. The test pyramid and a three-tier solution

The test pyramid places many fast unit tests at the bottom, fewer integration tests in the middle, and a small number of end-to-end tests at the top. If a business rule can be tested with a service and a fake repository, starting SQL Server is unnecessary. If the goal is to verify model binding, routing, dependency injection, middleware, and database behavior together, an integration test is more appropriate.

Test typeWhat it verifiesExample
Unit testOne class or business ruleIs a duplicate product rejected?
Integration testAPI, services, and data accessDoes a POST request return the correct response?
End-to-end testWeb, API, and user workflowCan a user create a product from the web interface?

2. Unit testing the application layer

Create a test project and reference the application project. The exact project names can be adjusted to match your solution.

dotnet new xunit -n Catalog.Tests dotnet sln add Catalog.Tests/Catalog.Tests.csproj dotnet add Catalog.Tests/Catalog.Tests.csproj reference Catalog.Application/Catalog.Application.csproj

Assume that the service has the following contract. The IProductRepository interface is the repository abstraction introduced earlier in the course.

public interface IProductService {    Task<ProductDto> CreateAsync(CreateProductRequest request,        CancellationToken cancellationToken = default); } public sealed class ProductService : IProductService {    private readonly IProductRepository _repository;    public ProductService(IProductRepository repository)        => _repository = repository;    public async Task<ProductDto> CreateAsync(        CreateProductRequest request,        CancellationToken cancellationToken = default)    {        if (string.IsNullOrWhiteSpace(request.Name))            throw new ValidationException("Product name is required.");        if (request.Price <= 0)            throw new ValidationException("Price must be greater than zero.");        var exists = await _repository.ExistsByNameAsync(            request.Name, cancellationToken);        if (exists)            throw new ConflictException("Product already exists.");        var product = new Product(request.Name.Trim(), request.Price);        await _repository.AddAsync(product, cancellationToken);        return new ProductDto(product.Id, product.Name, product.Price);    } }

Use a mock or a small fake repository instead of SQL Server in a unit test. A fake is often sufficient when only a few predictable behaviors are required.

public sealed class ProductServiceTests {    [Fact]    public async Task CreateAsync_RejectsNonPositivePrice()    {        var repository = new FakeProductRepository();        var service = new ProductService(repository);        var request = new CreateProductRequest("Keyboard", 0);        await Assert.ThrowsAsync<ValidationException>(() =>            service.CreateAsync(request));        Assert.Empty(repository.AddedProducts);    }    [Fact]    public async Task CreateAsync_AddsTrimmedProductWhenRequestIsValid()    {        var repository = new FakeProductRepository();        var service = new ProductService(repository);        var request = new CreateProductRequest("  Keyboard  ", 49.90m);        var result = await service.CreateAsync(request);        Assert.Equal("Keyboard", result.Name);        Assert.Equal(49.90m, result.Price);        Assert.Single(repository.AddedProducts);    } }

A good unit test describes behavior rather than implementation details. Naming the scenario and expected result makes failures easier to understand. Tests should be independent, deterministic, and free from unnecessary network, clock, file-system, or production-database dependencies.

3. Verifying API endpoints with integration tests

ASP.NET Core provides WebApplicationFactory<TEntryPoint> to start the application inside a test host. This makes it possible to exercise the HTTP pipeline, routing, model binding, dependency injection, controllers, and middleware. The test application must use an isolated database or test-specific data store. Connecting tests to a production database is never acceptable.

Add the application project and the ASP.NET Core testing package:

dotnet add Catalog.Tests package Microsoft.AspNetCore.Mvc.Testing dotnet add Catalog.Tests reference Catalog.Api/Catalog.Api.csproj

If Program is the application's entry point, a basic test can look like this:

public sealed class ProductApiTests    : IClassFixture<WebApplicationFactory<Program>> {    private readonly HttpClient _client;    public ProductApiTests(WebApplicationFactory<Program> factory)    {        _client = factory.WithWebHostBuilder(builder =>        {            builder.UseEnvironment("Testing");        }).CreateClient();    }    [Fact]    public async Task GetProducts_ReturnsOkAndJson()    {        var response = await _client.GetAsync("/api/products");        response.EnsureSuccessStatusCode();        Assert.Equal("application/json",            response.Content.Headers.ContentType?.MediaType);    }    [Fact]    public async Task CreateProduct_ReturnsCreated()    {        var payload = JsonContent.Create(new        {            name = "Keyboard",            price = 49.90        });        var response = await _client.PostAsync("/api/products", payload);        Assert.Equal(HttpStatusCode.Created, response.StatusCode);        Assert.NotNull(response.Headers.Location);    } }

When real SQL Server behavior must be tested, prepare a dedicated test database using migrations, seed known data, and clean it after the test run. SQLite or a test-container approach can make tests faster and more isolated, but database providers do not always implement identical SQL behavior. Provider-specific queries should therefore be tested against the provider used in production.

4. Structured logging

Logs are not merely messages for a developer. In production they help trace a request, correlate a failure, and understand system behavior. ASP.NET Core's ILogger<T> abstraction supports categories, log levels, and providers. Prefer it to Console.WriteLine so that filtering and centralized collection can be configured per environment.

public sealed class ProductService : IProductService {    private readonly IProductRepository _repository;    private readonly ILogger<ProductService> _logger;    public ProductService(        IProductRepository repository,        ILogger<ProductService> logger)    {        _repository = repository;        _logger = logger;    }    public async Task<ProductDto> CreateAsync(        CreateProductRequest request,        CancellationToken cancellationToken = default)    {        _logger.LogInformation(            "Creating product with name {ProductName}", request.Name);        // Apply business rules and persist the entity.        _logger.LogInformation(            "Product created with id {ProductId}", product.Id);        return result;    } }

{ProductName} and {ProductId} are structured properties. Message templates are preferable to string interpolation because log systems can index and filter those values. Never log passwords, access tokens, connection strings, or unnecessary personal data. Unexpected exceptions should be recorded by a centralized exception-handling middleware with LogError; clients should not receive internal stack traces.

{  "Logging": {    "LogLevel": {      "Default": "Information",      "Microsoft.AspNetCore": "Warning",      "Catalog": "Information"    }  } }

Verbose logging in production can increase storage cost and noise. Use Debug only when needed, and reserve error, warning, information, and critical levels for their intended meanings.

5. OpenAPI and Swagger documentation

API consumers should not have to guess routes, parameters, request bodies, or possible responses. OpenAPI describes this contract in a machine-readable format. In .NET 9 and later, ASP.NET Core includes built-in OpenAPI document generation. An interactive Swagger UI requires a separate UI package.

builder.Services.AddOpenApi(); var app = builder.Build(); if (app.Environment.IsDevelopment() ||    app.Environment.IsEnvironment("Staging")) {    app.MapOpenApi(); } app.MapControllers();

Improve the document with XML comments, response metadata, meaningful action names, and explicit status-code descriptions. Using CreatedAtAction for a successful create operation communicates both the 201 Created status and the location of the new resource. Before exposing documentation in production, evaluate access control and information-disclosure risks.

6. Environment configuration and production checklist

appsettings.json contains shared defaults, while appsettings.Development.json, appsettings.Testing.json, and appsettings.Production.json contain environment-specific values. Environment-specific configuration can override shared values, but secrets should not be committed as plain text. Use User Secrets during local development and environment variables or a secure secret store in production.

var connectionString = builder.Configuration    .GetConnectionString("DefaultConnection")    ?? throw new InvalidOperationException(        "DefaultConnection is not configured."); builder.Services.AddDbContext<CatalogDbContext>(options =>    options.UseSqlServer(connectionString));

Before deployment, verify the following:

  • Build: Does dotnet build --configuration Release complete without errors?
  • Tests: Do all tests pass with dotnet test --configuration Release?
  • Secrets: Are tokens and connection details absent from source control?
  • Error handling: Are detailed exception pages disabled in production?
  • Database: Is there a migration and rollback plan?
  • Health: Can application and database connectivity be monitored?
  • Logs: Are request context, severity, and useful diagnostic fields available?

7. Basic performance checks

Optimization without measurement is guesswork. Start with representative data and requests. Observe response time, requests per second, failure rate, CPU usage, and memory usage. The dotnet-counters tool can display runtime and ASP.NET Core counters for a running process.

dotnet tool update --global dotnet-counters dotnet-counters ps dotnet-counters monitor --process-id <PID> \  --counters Microsoft.AspNetCore.Hosting,System.Runtime

Common problems include excessive Include calls, returning large result sets without pagination, synchronous database operations, and repeating expensive work on every request. Use AsNoTracking for read-only queries when appropriate, and add indexes after examining real query patterns and execution plans. A small development database rarely represents production performance.

Short practice exercise

  1. Create the Catalog.Tests project and write at least three unit tests for ProductService.
  2. Use WebApplicationFactory to test the GET and POST product endpoints.
  3. Add appsettings.Testing.json and read the test connection string from it.
  4. Add two structured information logs to ProductService without logging sensitive data.
  5. Open the OpenAPI document and confirm that each endpoint describes its important response codes.
  6. Run the application in Release mode and observe it with dotnet-counters for at least two minutes. Record the results in a short table.

Conclusion

Production readiness is more than a deployment command. Unit tests protect business rules quickly; integration tests show that layers and endpoints work together. Structured logging makes incidents diagnosable, OpenAPI makes the API contract visible to other developers, and environment configuration separates development from production safely. Performance observation completes the process by replacing assumptions with evidence. In the final lesson, these practices will be combined with deployment, maintenance, and project completion activities.

Sources