<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rémi Despelchin on Medium]]></title>
        <description><![CDATA[Stories by Rémi Despelchin on Medium]]></description>
        <link>https://medium.com/@odinnou?source=rss-499cef748595------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*-nzbnWU7J9dtTEnW.png</url>
            <title>Stories by Rémi Despelchin on Medium</title>
            <link>https://medium.com/@odinnou?source=rss-499cef748595------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 11:25:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@odinnou/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building Caresse #3: Integration Testing a .NET API Without Touching Production]]></title>
            <link>https://medium.com/@odinnou/building-caresse-3-integration-testing-a-net-api-without-touching-production-1999f2ac35a8?source=rss-499cef748595------2</link>
            <guid isPermaLink="false">https://medium.com/p/1999f2ac35a8</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[hexagonal-architecture]]></category>
            <dc:creator><![CDATA[Rémi Despelchin]]></dc:creator>
            <pubDate>Thu, 04 Jun 2026 20:25:08 GMT</pubDate>
            <atom:updated>2026-06-06T18:13:00.781Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZiI6Ybzru6qGv8UVaeJVQQ.png" /></figure><blockquote>Third article in <strong>Building Caresse</strong> — inside the stack of a shipped, bootstrapped AI product. Previous: <a href="https://medium.com/@odinnou/building-caresse-1-hexagonal-architecture-for-a-multi-provider-ai-pipeline-f0c1ca4ee471">#1 hexagonal architecture</a>, <a href="https://medium.com/@odinnou/building-caresse-2-orchestrating-a-multi-phase-llm-pipeline-66f4a29ad236">#2 multi-phase LLM pipeline</a>.</blockquote><p><strong>Technical level:</strong> 🟩🟩🟦 Confirmed — assumes familiarity with ASP.NET Core, xUnit, and Docker basics.</p><p>The <a href="https://caresse.app/">Caresse</a> API depends on several external systems: PostgreSQL, Azure Blob Storage, Firebase (auth), RevenueCat (subscriptions), multiple LLM providers, and multiple TTS providers. In our integration test suite, none of them are the real thing.</p><ul><li>PostgreSQL runs in a Docker container spun up by TestContainers</li><li>Azure Blob Storage is replaced by Azurite, Microsoft’s local emulator</li><li>Firebase JWT validation is bypassed by a custom TestAuthHandler</li><li>RevenueCat, LLM providers, and TTS providers are all stubbed by WireMock.Net</li></ul><p>The suite runs in CI, takes under 90 seconds, and has never required a production credential. This article shows the full setup — every piece, wired together.</p><h3>Why integration tests, not unit tests</h3><p>This is worth addressing upfront, because the instinct on a project like this is to mock everything and keep tests fast. We did that at first. It bit us twice.</p><p>The first time: a PostgreSQL migration that passed all unit tests and crashed on apply against the real schema. The migration had a column rename; the NSubstitute mock didn’t care about column names. The real database did.</p><p>The second time: a change to how we serialized the RevenueCat webhook payload. The mock returned whatever we told it to — so the tests passed. The production handler silently dropped webhooks for two days before we caught it in the logs.</p><p>The failure mode with mocks isn’t that they’re wrong — it’s that they’re <em>too agreeable</em>. They return exactly what you tell them to, which means your tests only verify what you already assumed. Real HTTP contracts, real schema migrations, real serialization: these are the things that actually break in production, and mocks can’t surface them.</p><p>The setup in this article is more complex than a pure unit test suite. It’s also the reason we haven’t had a production incident from a broken integration in over six months.</p><h3>Project structure</h3><pre>tests/<br>└── Caresse.Api.IntegrationTests/<br>    ├── Fixtures/<br>    │   ├── ApiFactory.cs          # WebApplicationFactory + container wiring<br>    │   ├── PostgresFixture.cs     # TestContainers PostgreSQL<br>    │   └── WireMockFixture.cs     # WireMock server lifecycle<br>    ├── Helpers/<br>    │   └── AuthHelper.cs          # JWT generation for TestAuthHandler<br>    ├── Stubs/<br>    │   ├── OpenAiStubs.cs<br>    │   ├── ElevenLabsStubs.cs<br>    │   └── RevenueCatStubs.cs<br>    └── Tests/<br>        ├── GenerationTests.cs<br>        ├── SubscriptionTests.cs<br>        └── StorageTests.cs</pre><p>Everything flows through ApiFactory - one entry point, all dependencies wired in one place. Adding a new external dependency means touching exactly one file.</p><h3>Dependencies</h3><pre>&lt;PackageReference Include=&quot;Microsoft.AspNetCore.Mvc.Testing&quot; Version=&quot;9.*&quot; /&gt;<br>&lt;PackageReference Include=&quot;Testcontainers.PostgreSql&quot;        Version=&quot;3.*&quot; /&gt;<br>&lt;PackageReference Include=&quot;WireMock.Net&quot;                     Version=&quot;1.*&quot; /&gt;<br>&lt;PackageReference Include=&quot;xunit&quot;                            Version=&quot;2.*&quot; /&gt;<br>&lt;PackageReference Include=&quot;xunit.runner.visualstudio&quot;        Version=&quot;2.*&quot; /&gt;<br>&lt;PackageReference Include=&quot;FluentAssertions&quot;                 Version=&quot;6.*&quot; /&gt;</pre><p>Azurite ships as a Docker image — no NuGet package needed beyond Azure.Storage.Blobs which is already in the main project.</p><h3>1. TestContainers — real PostgreSQL in tests</h3><p>The standard approach for PostgreSQL in unit tests is to mock IRepository or inject an in-memory provider. Both approaches hide the thing most likely to break: the database schema, the migrations, and the actual SQL queries. TestContainers fixes this by spinning up a real PostgreSQL 16 container on test startup, running migrations against it, and tearing it down after.</p><pre>// Fixtures/PostgresFixture.cs<br>public sealed class PostgresFixture : IAsyncLifetime<br>{<br>    private readonly PostgreSqlContainer _container = new PostgreSqlBuilder()<br>        .WithImage(&quot;postgres:16-alpine&quot;)<br>        .WithDatabase(&quot;caresse_test&quot;)<br>        .WithUsername(&quot;test&quot;)<br>        .WithPassword(&quot;test&quot;)<br>        .WithCleanUp(true)<br>        .Build();<br><br>    public string ConnectionString =&gt; _container.GetConnectionString();<br><br>    public async Task InitializeAsync() =&gt; await _container.StartAsync();<br>    public async Task DisposeAsync()    =&gt; await _container.StopAsync();<br>}</pre><p>The container starts once per test collection, not once per test. This matters for speed — a fresh PostgreSQL container takes ~3 seconds to start; starting one per test would make the suite unusable. The xUnit mechanism that enables this is ICollectionFixture:</p><pre>[CollectionDefinition(&quot;Integration&quot;)]<br>public class IntegrationCollection : ICollectionFixture&lt;PostgresFixture&gt; { }<br><br>[Collection(&quot;Integration&quot;)]<br>public class GenerationTests(ApiFactory factory) : IClassFixture&lt;ApiFactory&gt; { ... }</pre><p>xUnit shares a single PostgresFixture instance across all tests in the &quot;Integration&quot; collection. Each test still runs in isolation - we reset the database state between tests using transactions or explicit cleanup, depending on the test scenario.</p><p>Migrations run automatically inside ApiFactory on first startup. The test database is always in the correct schema state before the first test assertion runs.</p><h3>2. Azurite — Azure Blob Storage without Azure</h3><p><a href="https://caresse.app/">Caresse</a> stores generated audio files in Azure Blob Storage. Testing storage operations against the real Azure service in CI would require a real connection string, a real storage account, and a real bill. Azurite — Microsoft’s official local emulator — eliminates all three.</p><p>Azurite runs as a Docker container alongside PostgreSQL:</p><pre>private readonly IContainer _azurite = new ContainerBuilder()<br>    .WithImage(&quot;mcr.microsoft.com/azure-storage/azurite&quot;)<br>    .WithPortBinding(10000, 10000)<br>    .WithWaitStrategy(Wait.ForUnixContainer().UntilPortIsAvailable(10000))<br>    .Build();</pre><p>The connection string uses Azurite’s hardcoded default credentials — these are published in the official documentation and are not secrets:</p><pre>public string AzuriteConnectionString =&gt;<br>    &quot;DefaultEndpointsProtocol=http;&quot; +<br>    &quot;AccountName=devstoreaccount1;&quot; +<br>    &quot;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tiqIBwJI/UDZCyDXlbWy0QYfA==;&quot; +<br>    &quot;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;&quot;;</pre><p>In ApiFactory, the real BlobServiceClient registration is overridden with one pointing at Azurite:</p><pre>services.AddSingleton(_ =&gt; new BlobServiceClient(azuriteConnectionString));</pre><p>Blob containers are created during fixture initialization so they exist before any test runs:</p><pre>var blobClient = new BlobServiceClient(AzuriteConnectionString);<br>await blobClient.CreateBlobContainerAsync(&quot;audio-output&quot;);<br>await blobClient.CreateBlobContainerAsync(&quot;assets&quot;);</pre><p>From that point on, every storage operation in the application code — upload, download, delete, existence check — runs against the local emulator with no code change in the adapter. The IBlobStoragePort implementation doesn&#39;t know it&#39;s talking to Azurite.</p><h3>3. TestAuthHandler — bypassing Firebase JWT</h3><p>Firebase authentication works by validating a JWT against Google’s public key endpoint. In tests, we have two problems: we don’t want a network call to Google on every test run, and we can’t realistically issue valid Firebase tokens from CI without a service account.</p><p>The solution is to replace the entire authentication handler at test startup — not mock it, <em>replace</em> it. The production application code that reads user_id from claims doesn&#39;t change at all; only the mechanism that populates those claims is swapped.</p><p>The test token is deliberately simple — just a base64-encoded user ID:</p><pre>// Helpers/AuthHelper.cs<br>public static class AuthHelper<br>{<br>    public const string TestUserId = &quot;test-user-uid-001&quot;;<br>    public const string Scheme     = &quot;TestAuth&quot;;<br><br>    public static string GenerateToken(string userId = TestUserId) =&gt;<br>        Convert.ToBase64String(Encoding.UTF8.GetBytes(userId));<br>}</pre><p>The handler decodes it and builds a ClaimsPrincipal with the same claim structure that Firebase would have produced:</p><pre>// TestAuthHandler.cs<br>public sealed class TestAuthHandler(<br>    IOptionsMonitor&lt;AuthenticationSchemeOptions&gt; options,<br>    ILoggerFactory logger,<br>    UrlEncoder encoder)<br>    : AuthenticationHandler&lt;AuthenticationSchemeOptions&gt;(options, logger, encoder)<br>{<br>    protected override Task&lt;AuthenticateResult&gt; HandleAuthenticateAsync()<br>    {<br>        var userId = Context.Request.Headers.Authorization<br>            .ToString()<br>            .Replace(&quot;Bearer &quot;, &quot;&quot;);<br><br>        if (string.IsNullOrEmpty(userId))<br>            return Task.FromResult(AuthenticateResult.Fail(&quot;No token&quot;));<br><br>        var decoded = Encoding.UTF8.GetString(Convert.FromBase64String(userId));<br><br>        var claims = new[]<br>        {<br>            new Claim(ClaimTypes.NameIdentifier, decoded),<br>            new Claim(&quot;user_id&quot;, decoded),<br>        };<br><br>        var identity  = new ClaimsIdentity(claims, Scheme);<br>        var principal = new ClaimsPrincipal(identity);<br>        var ticket    = new AuthenticationTicket(principal, Scheme);<br><br>        return Task.FromResult(AuthenticateResult.Success(ticket));<br>    }<br>}</pre><p>In ApiFactory, Firebase is removed and TestAuthHandler is registered in its place:</p><pre>builder.ConfigureServices(services =&gt;<br>{<br>    var firebaseDescriptor = services<br>        .SingleOrDefault(d =&gt; d.ServiceType == typeof(IAuthenticationSchemeProvider));<br>    if (firebaseDescriptor != null)<br>        services.Remove(firebaseDescriptor);<br><br>    services<br>        .AddAuthentication(AuthHelper.Scheme)<br>        .AddScheme&lt;AuthenticationSchemeOptions, TestAuthHandler&gt;(<br>            AuthHelper.Scheme, _ =&gt; { });<br>});</pre><p>In tests, authenticating is one line — and it works for any user ID you need to simulate:</p><pre>client.DefaultRequestHeaders.Authorization =<br>    new AuthenticationHeaderValue(&quot;Bearer&quot;, AuthHelper.GenerateToken());<br><br>// or, to test a specific user scenario:<br>client.DefaultRequestHeaders.Authorization =<br>    new AuthenticationHeaderValue(&quot;Bearer&quot;, AuthHelper.GenerateToken(&quot;premium-user-uid-002&quot;));</pre><p>No Firebase project, no service account, no network. Every endpoint that requires authentication behaves identically to production.</p><h3>4. WireMock.Net — stubbing RevenueCat, LLM providers, and TTS</h3><p>WireMock.Net runs as an in-process HTTP server that intercepts outbound HTTP calls. Every external HTTP API that we can’t or shouldn’t call in CI goes through it: RevenueCat, all LLM providers (OpenAI, Grok, DeepSeek…), and all TTS providers (ElevenLabs, Cartesia…).</p><p>The server starts once and stays up for the duration of the test run:</p><pre>// Fixtures/WireMockFixture.cs<br>public sealed class WireMockFixture : IAsyncLifetime<br>{<br>    public WireMockServer Server { get; private set; } = null!;<br><br>    public Task InitializeAsync()<br>    {<br>        Server = WireMockServer.Start(new WireMockServerSettings<br>        {<br>            Port = 9090,<br>            StartAdminInterface = false,<br>        });<br>        return Task.CompletedTask;<br>    }<br><br>    public Task DisposeAsync()<br>    {<br>        Server.Stop();<br>        return Task.CompletedTask;<br>    }<br>}</pre><p><strong>LLM providers.</strong> For OpenAI, Grok, DeepSeek and others, WireMock returns a fixed completion response. The goal isn’t to test model output quality — it’s to verify that the pipeline correctly routes to the right endpoint, sends the right headers, handles the response shape, and passes the output to the next stage. A static placeholder is exactly the right level of fidelity for that:</p><pre>// Stubs/OpenAiStubs.cs<br>public static void RegisterCompletion(WireMockServer server, string apiKey) =&gt;<br>    server<br>        .Given(Request.Create()<br>            .WithPath(&quot;/v1/chat/completions&quot;)<br>            .WithHeader(&quot;Authorization&quot;, $&quot;Bearer {apiKey}&quot;)<br>            .UsingPost())<br>        .RespondWith(Response.Create()<br>            .WithStatusCode(200)<br>            .WithHeader(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>            .WithBodyAsJson(new<br>            {<br>                id      = &quot;chatcmpl-test&quot;,<br>                choices = new[]<br>                {<br>                    new<br>                    {<br>                        message      = new { role = &quot;assistant&quot;, content = &quot;Stage output placeholder.&quot; },<br>                        finish_reason = &quot;stop&quot;<br>                    }<br>                },<br>                usage = new { prompt_tokens = 10, completion_tokens = 20, total_tokens = 30 }<br>            }));</pre><p><strong>TTS providers.</strong> TTS stubs return a minimal but valid audio payload — a real MP3 header stored as a byte array in the test project. This is important: if the stub returns an empty body, the audio assembly stage will fail downstream. The stub needs to be <em>valid enough</em> for the pipeline to proceed end-to-end:</p><pre>// Stubs/ElevenLabsStubs.cs<br>public static void RegisterTts(WireMockServer server, string apiKey) =&gt;<br>    server<br>        .Given(Request.Create()<br>            .WithPath(&quot;/v1/text-to-speech/*&quot;)<br>            .WithHeader(&quot;xi-api-key&quot;, apiKey)<br>            .UsingPost())<br>        .RespondWith(Response.Create()<br>            .WithStatusCode(200)<br>            .WithHeader(&quot;Content-Type&quot;, &quot;audio/mpeg&quot;)<br>            .WithBody(TestAudioFixtures.MinimalMp3));</pre><p><strong>RevenueCat.</strong> Subscription stubs are registered per-scenario, not globally. This lets each test declare exactly what RevenueCat returns for its specific case — active subscription, expired, never subscribed, webhook event — without stubs bleeding across tests:</p><pre>// inside a test<br>RevenueCatStubs.RegisterActiveSubscription(_wireMock.Server, AuthHelper.TestUserId);<br><br>var response = await _client.GetAsync(&quot;/api/subscription/status&quot;);</pre><p>The static stub builders ( OpenAiStubs, ElevenLabsStubs, RevenueCatStubs) keep test bodies readable. The JSON shapes live in one place and are reused across the entire suite.</p><p>In ApiFactory, all external base URLs are overridden to point at WireMock:</p><pre>config.AddInMemoryCollection(new Dictionary&lt;string, string?&gt;<br>{<br>    [&quot;RevenueCat:BaseUrl&quot;] = &quot;http://localhost:9090&quot;,<br>    [&quot;OpenAi:BaseUrl&quot;]     = &quot;http://localhost:9090&quot;,<br>    [&quot;ElevenLabs:BaseUrl&quot;] = &quot;http://localhost:9090&quot;,<br>});</pre><p>The production HttpClient instances for every provider hit localhost:9090 in tests. No change in the adapters.</p><h3>5. ApiFactory — wiring it all together</h3><p>ApiFactory is the single assembly point. It owns the container lifecycle, overrides configuration, and swaps authentication:</p><pre>public sealed class ApiFactory : WebApplicationFactory&lt;Program&gt;, IAsyncLifetime<br>{<br>    private readonly PostgresFixture _postgres = new();<br>    private readonly WireMockFixture _wireMock = new();<br><br>    public WireMockServer WireMock =&gt; _wireMock.Server;<br><br>    public async Task InitializeAsync()<br>    {<br>        await _postgres.InitializeAsync();<br>        await _wireMock.InitializeAsync();<br>    }<br><br>    public new async Task DisposeAsync()<br>    {<br>        await _postgres.DisposeAsync();<br>        await _wireMock.DisposeAsync();<br>    }<br><br>    protected override void ConfigureWebHost(IWebHostBuilder builder)<br>    {<br>        builder.ConfigureAppConfiguration((_, config) =&gt;<br>        {<br>            config.AddInMemoryCollection(new Dictionary&lt;string, string?&gt;<br>            {<br>                [&quot;ConnectionStrings:Default&quot;]    = _postgres.ConnectionString,<br>                [&quot;Azure:BlobStorage:Connection&quot;] = _postgres.AzuriteConnectionString,<br>                [&quot;RevenueCat:BaseUrl&quot;]           = &quot;http://localhost:9090&quot;,<br>                [&quot;OpenAi:BaseUrl&quot;]               = &quot;http://localhost:9090&quot;,<br>                [&quot;ElevenLabs:BaseUrl&quot;]           = &quot;http://localhost:9090&quot;,<br>            });<br>        });<br><br>        builder.ConfigureServices(services =&gt;<br>        {<br>            RemoveFirebaseAuth(services);<br>            services<br>                .AddAuthentication(AuthHelper.Scheme)<br>                .AddScheme&lt;AuthenticationSchemeOptions, TestAuthHandler&gt;(<br>                    AuthHelper.Scheme, _ =&gt; { });<br><br>            var sp = services.BuildServiceProvider();<br>            using var scope = sp.CreateScope();<br>            var db = scope.ServiceProvider.GetRequiredService&lt;AppDbContext&gt;();<br>            db.Database.Migrate();<br>        });<br>    }<br><br>    private static void RemoveFirebaseAuth(IServiceCollection services)<br>    {<br>        var descriptor = services.SingleOrDefault(<br>            d =&gt; d.ServiceType == typeof(IAuthenticationSchemeProvider));<br>        if (descriptor != null) services.Remove(descriptor);<br>    }<br>}</pre><p>Tests receive ApiFactory via IClassFixture&lt;ApiFactory&gt; and call factory.CreateClient(). That client hits the real ASP.NET Core pipeline, with the real middleware, the real DI container, and real adapters - just with local infrastructure underneath.</p><h3>6. Writing the tests</h3><p>Convention throughout the suite: Method_Condition_ShouldBehavior. It&#39;s mechanical, but it pays back when a test fails at 2am and you need to know at a glance what broke and under what condition.</p><pre>[Collection(&quot;Integration&quot;)]<br>public class SubscriptionTests(ApiFactory factory) : IClassFixture&lt;ApiFactory&gt;<br>{<br>    private readonly HttpClient _client = factory.CreateClient();<br><br>    [Fact]<br>    public async Task GetStatus_WithActiveSubscription_ShouldReturnPremium()<br>    {<br>        _client.DefaultRequestHeaders.Authorization =<br>            new AuthenticationHeaderValue(&quot;Bearer&quot;, AuthHelper.GenerateToken());<br><br>        RevenueCatStubs.RegisterActiveSubscription(factory.WireMock, AuthHelper.TestUserId);<br><br>        var response = await _client.GetAsync(&quot;/api/subscription/status&quot;);<br>        var body     = await response.Content.ReadFromJsonAsync&lt;SubscriptionStatusDto&gt;();<br><br>        response.StatusCode.Should().Be(HttpStatusCode.OK);<br>        body!.Tier.Should().Be(&quot;premium&quot;);<br>        body.ExpiresAt.Should().BeAfter(DateTime.UtcNow);<br>    }<br><br>    [Fact]<br>    public async Task GetStatus_WithExpiredSubscription_ShouldReturnFree()<br>    {<br>        _client.DefaultRequestHeaders.Authorization =<br>            new AuthenticationHeaderValue(&quot;Bearer&quot;, AuthHelper.GenerateToken());<br><br>        RevenueCatStubs.RegisterExpiredSubscription(factory.WireMock, AuthHelper.TestUserId);<br><br>        var response = await _client.GetAsync(&quot;/api/subscription/status&quot;);<br>        var body     = await response.Content.ReadFromJsonAsync&lt;SubscriptionStatusDto&gt;();<br><br>        response.StatusCode.Should().Be(HttpStatusCode.OK);<br>        body!.Tier.Should().Be(&quot;free&quot;);<br>    }<br>}</pre><p>Each test is self-contained: it sets up its own WireMock stubs, makes one HTTP call, and asserts on the response. No shared mutable state, no test ordering dependencies.</p><h3>7. CI configuration</h3><p>One of the practical wins of this setup is how little the CI configuration needs to do:</p><pre># .github/workflows/tests.yml<br>jobs:<br>  integration-tests:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v4<br><br>      - name: Setup .NET<br>        uses: actions/setup-dotnet@v4<br>        with:<br>          dotnet-version: &#39;10.x&#39;<br><br>      - name: Run integration tests<br>        run: dotnet test tests/Caresse.Api.IntegrationTests --configuration Release</pre><p>No services: block, no docker-compose, no environment variables for external APIs. TestContainers pulls the PostgreSQL and Azurite images at runtime - Docker is available on ubuntu-latest out of the box. WireMock is in-process. The runner needs nothing pre-installed beyond .NET and Docker.</p><p>Total runtime: ~85 seconds on a cold runner (image pull included), ~40 seconds on a warm runner with cached images. For a suite that covers the full request lifecycle across every external dependency, that’s acceptable.</p><h3>What this replaces</h3><p>Before this setup, the test strategy was unit tests with NSubstitute mocks for everything external, plus manual QA against a shared staging environment before each release.</p><p>The mocks gave false confidence: they verified that our code called the right methods, not that the right things happened. The staging environment was a bottleneck: only one person could run a meaningful end-to-end test at a time, and “it works on staging” was often wrong by the time it mattered.</p><p>The integration suite replaced both. Every PR now runs against a real database with the real schema and real migrations, real blob storage operations, and real HTTP contracts for every provider. The only things that aren’t real are the vendors we can’t run locally — and for those, WireMock enforces the actual HTTP contract, not a hand-rolled assumption. The pipeline runs end-to-end: prompt in, audio bytes out, every adapter exercised, no real API key required.</p><h3>Coming next in Building Caresse</h3><p><strong>Building Caresse #4</strong> covers multi-provider LLM integration: the IPromptExecutorPort interface, how five different vendors implement it, how we handle streaming vs. non-streaming APIs in a unified way, and the NSubstitute tests that make provider swaps safe.</p><p>Follow on Medium to catch it when it drops.</p><h3>See it running</h3><ul><li>🌐 <a href="https://caresse.app/"><strong>caresse.app</strong></a> — overview, supported languages (FR / EN / ES)</li><li>📱 <a href="https://play.google.com/store/apps/details?id=com.flareai.caresse"><strong>Caresse on Google Play</strong></a></li></ul><p><em>Found a better approach to any of these? Reply on Medium — I read every message.</em></p><p><strong>Series:</strong> Building Caresse — inside the stack of a bootstrapped AI product. <strong>Previous — #2:</strong> <a href="https://medium.com/@odinnou/building-caresse-2-orchestrating-a-multi-phase-llm-pipeline-66f4a29ad236">the multi-phase LLM pipeline</a>. <strong>Next up — #4:</strong> multi-provider LLM integration with ports &amp; adapters.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1999f2ac35a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Caresse #2: Orchestrating a Multi-Phase LLM Pipeline]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@odinnou/building-caresse-2-orchestrating-a-multi-phase-llm-pipeline-66f4a29ad236?source=rss-499cef748595------2"><img src="https://cdn-images-1.medium.com/max/1774/1*hr24axQNj_VLDsxjmrdr3Q.png" width="1774"></a></p><p class="medium-feed-snippet">This is the second article in Building Caresse, a series taking you inside the architecture of a shipped, bootstrapped AI product &#x2014; the&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@odinnou/building-caresse-2-orchestrating-a-multi-phase-llm-pipeline-66f4a29ad236?source=rss-499cef748595------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@odinnou/building-caresse-2-orchestrating-a-multi-phase-llm-pipeline-66f4a29ad236?source=rss-499cef748595------2</link>
            <guid isPermaLink="false">https://medium.com/p/66f4a29ad236</guid>
            <category><![CDATA[hexagonal-architecture]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Rémi Despelchin]]></dc:creator>
            <pubDate>Tue, 02 Jun 2026 19:30:14 GMT</pubDate>
            <atom:updated>2026-06-06T18:12:18.791Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Building Caresse #1: Hexagonal Architecture for a Multi-Provider AI Pipeline]]></title>
            <link>https://medium.com/@odinnou/building-caresse-1-hexagonal-architecture-for-a-multi-provider-ai-pipeline-f0c1ca4ee471?source=rss-499cef748595------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0c1ca4ee471</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[hexagonal-architecture]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Rémi Despelchin]]></dc:creator>
            <pubDate>Mon, 01 Jun 2026 18:38:59 GMT</pubDate>
            <atom:updated>2026-06-06T18:11:35.093Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ytom68t1spMTMSCI76MFg.png" /></figure><blockquote>This is the first article in <strong>Building Caresse</strong>, a new series taking you inside the architecture of a shipped, bootstrapped AI product — the .NET 10 backend, the Kotlin Multiplatform app, the trade-offs, the dead ends. Every article draws from the production codebase behind <a href="https://caresse.app/">caresse.app</a>.</blockquote><p><strong>Technical level:</strong> 🟩🟩🟦 Confirmed — assumes you’re comfortable with C#, .NET DI, and have at least heard of ports &amp; adapters. No prior DDD theory required.</p><p>Most articles about hexagonal architecture stop at the diagram. You get the hexagon, the two kinds of arrows, a vague reference to Alistair Cockburn — and then a toy example with one repository and one controller. That’s not architecture, that’s a folder rename.</p><p>This article is different. It walks through how we structured the real .NET 10 API behind <a href="https://caresse.app/"><strong>Caresse</strong></a> — an immersive-audio app <a href="https://play.google.com/store/apps/details?id=com.flareai.caresse">live on the Play Store</a> — that orchestrates <strong>five LLM providers</strong> (OpenAI, Grok, DeepSeek, OpenRouter, Mistral) and <strong>six TTS providers</strong> behind a single internal contract, runs a multi-stage generation pipeline, and ships audio to mobile.</p><p>The headline result: <strong>the domain has not been edited a single time when we added or replaced a provider in the last six months.</strong> Not when we swapped one LLM for another on a specific stage. Not when a cheaper provider joined to cut costs on the easy parts. Not when we changed TTS engines for one specific language because another vendor turned out to be better at it.</p><p>If you’ve ever tried to bolt a second LLM into a codebase that “just used OpenAI,” you already know what this article is about.</p><h3>Why we needed real boundaries</h3><p>Our API does one thing on paper: turn a structured prompt into an immersive audio file. In practice, it has to:</p><ol><li>Decide which LLM to call <strong>for each generation stage</strong> (the pipeline has multiple — more on that in a future article)</li><li>Stream tokens or wait for completion depending on the provider’s API style</li><li>Route each generated line to a TTS provider chosen per voice and language</li><li>Mix the resulting audio tracks with ambient music</li><li>Persist the result, charge the user via RevenueCat, handle webhooks</li></ol><p>Every one of those steps depends on something external — and every one of those externals <strong>will</strong> change. Providers raise prices, deprecate models, get rate-limited, get acquired. OpenAI’s API changes shape twice a year. Voice models that used to be the gold standard get replaced by upstart competitors in months. The cost of a “small” change to an external service ripples through any codebase that doesn’t have real boundaries.</p><p>If the use case at the center of our domain knows the string “OpenAI” anywhere — in a class name, in a method call, in a config key — we’ve already lost. That’s the test for hexagonal:</p><blockquote><strong><em>Can you grep your domain for vendor names and get zero hits?</em></strong></blockquote><p>For us, the answer is zero. Here’s how we got there.</p><h3>The folder structure that actually matters</h3><p>Here’s the layout we converged on after two refactors:</p><pre>src/<br>├── Caresse.Domain/<br>│   ├── Models/                  # Pure C# records, no attributes<br>│   ├── Ports/<br>│   │   ├── Driving/             # What the outside world calls INTO us<br>│   │   └── Driven/              # What WE call OUT to<br>│   └── UseCases/                # The actual business logic<br>│<br>├── Caresse.DrivingAdapters/     # HTTP, gRPC, CLI, webhooks<br>│   └── Rest/<br>│<br>└── Caresse.DrivenAdapters/      # Implementations of the driven ports<br>    ├── Llm/                     # One adapter per LLM provider<br>    ├── Tts/                     # One adapter per TTS provider<br>    ├── Persistence/<br>    └── Audio/                   # Audio post-processing</pre><p>The naming conventions matter more than they look:</p><ul><li><strong>I*Port</strong> for any interface defined inside the domain. Never I*Service, never I*Repository. The name reminds you that the domain <em>owns</em> the contract - adapters implement it, not the other way around.</li><li><strong>*UseCase</strong> for the orchestrators. One use case = one user-visible operation. If your &quot;use case&quot; is doing two things, split it.</li><li><strong>*RestAdapter</strong> (not *Controller) for the HTTP layer. ASP.NET happens to provide controllers, but our code shouldn&#39;t pretend HTTP is the only entry point - tomorrow it could be a gRPC adapter, a queue handler, or a CLI.</li><li><strong>*Adapter</strong> suffix for <em>every</em> driven implementation. When you see something named *PromptAdapter, you know immediately it&#39;s an outbound implementation talking to the outside world, not domain logic.</li></ul><p>These aren’t cosmetic rules. They’re how a new contributor finds the right file in under a minute — and how a senior reviewer catches “this shouldn’t live here” in a glance at the PR diff.</p><h3>What we tried first (and abandoned)</h3><p>The first version of this API was the controller-knows-everything style. One controller, ~600 lines, that did the LLM call, the TTS call, the EF Core save, and the HTTP response in sequence. It worked. Until it didn’t.</p><p>The first time we needed to swap LLM vendors for one specific stage of the pipeline, the diff touched the controller, the config, three test files, and we ended up with a feature flag branch that everyone hated within a week.</p><p>We then tried the classic “service layer” — extract OpenAiService, ElevenLabsService, inject them into the controller. Better, but still wrong: the controller now knew there were <em>two</em> providers, and adding a third meant editing the controller again. The dependency was still in the wrong direction.</p><p>The third attempt was hexagonal done badly: we made interfaces, but they lived in the same project as their implementations, and the use cases imported the implementation namespace “just for the DTOs.” Every shortcut compounded. Within two months we had circular references and [InternalsVisibleTo] attributes patching over leaky abstractions.</p><p>The current architecture works because we drew <strong>three hard lines</strong>:</p><ol><li>The domain project has <strong>zero NuGet dependencies</strong> except System.*. No EF Core, no HttpClient, no Serilog.</li><li>Domain ports define their <strong>own DTOs</strong>. Adapters translate between port DTOs and vendor DTOs.</li><li><strong>Compile-time enforcement</strong>: a CI step runs dotnet list package --include-transitive on the Domain project and fails if anything outside an allowlist appears.</li></ol><p>If those three lines aren’t enforced, “hexagonal architecture” is just folder theater.</p><h3>The provider registry pattern</h3><p>This is the piece that nobody publishes, so here’s the shape — without giving away the whole thing.</p><p>The domain knows about an enum:</p><pre>public enum AiProvider { OpenAi, Grok, DeepSeek, OpenRouter, Mistral }</pre><p>And a port (one method, no vendor leakage):</p><pre>public interface IPromptExecutorPort<br>{<br>    AiProvider Provider { get; }<br>    Task&lt;PromptResult&gt; ExecuteAsync(Prompt prompt, CancellationToken ct);<br>}</pre><p>Each adapter implements the port and declares which provider it handles. There is <strong>no</strong> base class, no shared HTTP helper, no “smart” abstraction layer — every vendor has its own quirks and we let each adapter own them. Trying to factor out commonality between LLM HTTP clients was one of our worst time sinks; we tore it out.</p><p>The wiring is where the magic — really, the lack of magic — happens. In Program.cs:</p><pre>builder.Services.AddSingleton&lt;IPromptExecutorPort, OpenAiPromptAdapter&gt;();<br>builder.Services.AddSingleton&lt;IPromptExecutorPort, GrokPromptAdapter&gt;();<br>// ... one line per provider<br><br>builder.Services.AddSingleton&lt;IReadOnlyDictionary&lt;AiProvider, IPromptExecutorPort&gt;&gt;(sp =&gt;<br>    sp.GetServices&lt;IPromptExecutorPort&gt;().ToDictionary(a =&gt; a.Provider));</pre><p>That dictionary is what the use case receives. Selecting a provider becomes a single lookup:</p><pre>var executor = llms[stage.Provider];<br>var result = await executor.ExecuteAsync(stage.ToPrompt(context), ct);  </pre><p>The same pattern applies to TTS — different enum, different port, same registry shape. Same goes for audio post-processing: one port, one adapter, the domain never sees the implementation.</p><p>Adding a new provider is exactly three things:</p><ol><li>Add a value to the enum</li><li>Create a new *PromptAdapter class implementing the port</li><li>Register it in Program.cs</li></ol><p>The use case, the domain models, and the controllers are all unchanged. The compiler tells you if you missed a case somewhere — and there shouldn’t be any, because the dictionary is exhaustive by construction.</p><p>When we added a new vendor mid-pipeline to cut costs on the cheaper stages of <a href="https://caresse.app/">Caresse</a> ‘s generator, the diff was under 50 lines. Zero in the domain.</p><h3>Testing the adapters in isolation</h3><p>This architecture only pays off if you can also test each piece in isolation. Two layers, two strategies:</p><ul><li><strong>Adapter tests</strong> verify the <em>protocol</em> with one vendor — using a fake HttpMessageHandler to simulate vendor responses, no network involved. One adapter at a time, one vendor at a time, deterministic.</li><li><strong>Use case tests</strong> substitute the <strong>entire dictionary</strong> of ports. The orchestration logic is exercised with no vendor at all, just Substitute.For&lt;IPromptExecutorPort&gt;() instances asserting &quot;this stage called this executor.&quot;</li></ul><p>The combination matters: adapter tests cover the integration surface, use case tests cover the business rules. Together they replace a brittle end-to-end suite that used to take 12 minutes and pass 70% of the time.</p><pre>// shape only — use case test<br>await useCase.ExecuteAsync(request, ct);<br><br>await openAi.Received(1).ExecuteAsync(Arg.Any&lt;Prompt&gt;(), Arg.Any&lt;CancellationToken&gt;());<br>await grok.Received(1).ExecuteAsync(Arg.Any&lt;Prompt&gt;(), Arg.Any&lt;CancellationToken&gt;());</pre><p>Zero HTTP, zero database, runs in milliseconds. Every PR runs the full suite.</p><h3>What it costs you</h3><p>I’d be lying if I said the architecture is free.</p><ul><li><strong>More files.</strong> You will have three or four files where the controller-only version had one. New devs will ask “why” for the first week.</li><li><strong>More indirection in stack traces.</strong> A call goes RestAdapter → UseCase → Port → Adapter. That’s four frames where there used to be one.</li><li><strong>The registry pattern is opaque to newcomers.</strong> “Where does this port come from?” is a real question, and the answer (Program.cs registers all of them, the use case receives a dictionary) is not obvious from any single file.</li><li><strong>You will be tempted to leak.</strong> “Just this once” — a JsonPropertyName attribute in a domain model because it&#39;s easier than mapping. Don&#39;t. The day you say yes, the architecture starts dying.</li></ul><p>We accept these costs because <a href="https://caresse.app/">Caresse</a> has crossed the threshold where they pay back: we genuinely swap providers per stage, we genuinely test each adapter in isolation, and we genuinely run the same use cases from HTTP, webhooks, and background jobs. If you’re building a CRUD app with one database and one external API, hexagonal is probably overkill — and that’s a fine conclusion to come away with.</p><h3>The grep test</h3><p>Try it on your own code:</p><pre>grep -rE &quot;OpenAI|ElevenLabs|Cartesia|Grok|DeepSeek&quot; src/YourApp.Domain/</pre><p>If you get zero results, your domain is genuinely decoupled. If you get a hit, that’s your next refactor.</p><p>For us, the answer is zero — and that’s the only metric that matters when the next provider war breaks out and we need to switch in an afternoon.</p><h3>Coming next in Building Caresse</h3><p>The registry pattern explains <em>how</em> we route to providers. <strong>Building Caresse #2</strong> explains <em>why we route at all</em>: the multi-stage generation pipeline at the heart of <a href="https://caresse.app/">Caresse</a>, where one user prompt becomes a full multi-voice scene, with a different model per stage and a self-critique step that improves the output before it ever reaches TTS.</p><p>It also covers the hardest lesson we learned: <strong>one big prompt fails where several smaller, chained ones succeed</strong>, and the failure mode looks like quality regression rather than an error in the logs. We had to build per-stage evaluation to catch it.</p><p>If this article was useful, follow me on Medium so you don’t miss #2 — it’s where this architecture starts paying for itself.</p><h3>See it running</h3><p>This isn’t a thought experiment — it’s the backend of a shipped product:</p><ul><li>🌐 <a href="https://caresse.app/"><strong>caresse.app</strong></a> — overview, concept and screenshots</li><li>📱 <a href="https://play.google.com/store/apps/details?id=com.flareai.caresse"><strong>Caresse on Google Play</strong></a> — live, iOS coming</li></ul><p><em>Questions, pushback, or want me to dig into a specific layer? Reply on Medium or reach out via </em><a href="https://caresse.app/"><em>caresse.app</em></a><em> — I read every message and the next article topic often comes from reader questions.</em></p><p><strong>Series:</strong> Building Caresse — inside the stack of a bootstrapped AI product. <strong>Next up — #2:</strong> <a href="https://medium.com/@odinnou/building-caresse-2-orchestrating-a-multi-phase-llm-pipeline-66f4a29ad236">the multi-stage LLM pipeline</a> that turns one prompt into an immersive scene.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0c1ca4ee471" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CronJob K8s in .NET: the right way]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@odinnou/cronjob-k8s-in-net-the-right-way-3fb137dc6a87?source=rss-499cef748595------2"><img src="https://cdn-images-1.medium.com/max/1920/1*d_r3CykECXaw_w3aHGE-yQ.png" width="1920"></a></p><p class="medium-feed-snippet">&#x1F7E9;&#x1F7E9;&#x1F7E9; Expert</p><p class="medium-feed-link"><a href="https://medium.com/@odinnou/cronjob-k8s-in-net-the-right-way-3fb137dc6a87?source=rss-499cef748595------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@odinnou/cronjob-k8s-in-net-the-right-way-3fb137dc6a87?source=rss-499cef748595------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fb137dc6a87</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Rémi Despelchin]]></dc:creator>
            <pubDate>Wed, 29 Mar 2023 18:37:41 GMT</pubDate>
            <atom:updated>2023-03-30T07:14:30.382Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Integration Testing in .NET: the right way]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@odinnou/integration-testing-in-net-the-right-way-3a2e73d6cefb?source=rss-499cef748595------2"><img src="https://cdn-images-1.medium.com/max/1920/1*CbjyuxgAMqZX_2Dx52JR7g.png" width="1920"></a></p><p class="medium-feed-snippet">&#x1F7E9;&#x1F7E9;&#x1F7E6; Confirmed</p><p class="medium-feed-link"><a href="https://medium.com/@odinnou/integration-testing-in-net-the-right-way-3a2e73d6cefb?source=rss-499cef748595------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@odinnou/integration-testing-in-net-the-right-way-3a2e73d6cefb?source=rss-499cef748595------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a2e73d6cefb</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-craftsmanship]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[software-testing]]></category>
            <dc:creator><![CDATA[Rémi Despelchin]]></dc:creator>
            <pubDate>Mon, 23 Jan 2023 21:28:23 GMT</pubDate>
            <atom:updated>2023-01-23T21:28:23.922Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Hexagonal Architecture in .NET: the fastest (right) way]]></title>
            <link>https://medium.com/@odinnou/hexagonal-architecture-in-net-the-fastest-right-way-df93bec46bff?source=rss-499cef748595------2</link>
            <guid isPermaLink="false">https://medium.com/p/df93bec46bff</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Rémi Despelchin]]></dc:creator>
            <pubDate>Thu, 13 Oct 2022 19:56:35 GMT</pubDate>
            <atom:updated>2023-01-05T20:52:40.915Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y1E1PBNtaQjhCF6PJToVjA.png" /></figure><h3>Hexagonal Architecture in .NET: the fastest (right) way</h3><p>🟩🟩🟦 <em>Confirmed</em></p><blockquote>My goal is to provide you with a quick and easy-to-implement solution in order to adapt this architecture to your project. This story is .NET-oriented, but you could adjust its content for Java without effort.</blockquote><h3>Overview</h3><p>Hexagonal Architecture has the wind in its sails. There are many blog posts about <a href="https://blog.octo.com/hexagonal-architecture-three-principles-and-an-implementation-example/">the theory</a> but much fewer about practicals.<br>But I need to introduce it before switching to the code.</p><h4>Domain:</h4><p>It’s the core of the system where all the business logic resides. We want to isolate it from both the driving and driven sides. <br>Just remember one thing: <strong>no infrastructure code in the domain</strong>.<strong> </strong><em>(ex: Microsoft.AspNetCore.* or Microsoft.EntityFrameworkCore.* are forbidden here).</em></p><h4>Driving (or primary) side:</h4><p>Driving (or primary) actors are the ones that initiate the interaction with the application. <br>Typically, your HTTP routes for an API or a Kafka consumer.<strong> </strong><em>(ex: Microsoft.AspNetCore.* should be found here).</em></p><h4>Driven (or secondary) side:</h4><p>The layer where we’ll find what your application needs, for example, a database adapter, is called by the application so that it fetches a specific data set from persistence.<strong> </strong><em>(ex: Microsoft.EntityFrameworkCore.* should be found here).</em></p><h4>Main benefits:</h4><ul><li>Easy to maintain: thanks to the decoupling provided by the hexagonal architecture, it is easy to add features without leading to refactoring. Indeed, changes in one area of the application don’t affect others.</li><li>Easy to test: thanks to interfaces, you can mock dependencies and test each layer in isolation, as I have described <a href="https://medium.com/@odinnou/unit-testing-in-net-the-right-way-f8754836b605">here</a>.</li></ul><p>The term “hexagonal” comes from the graphical conventions that show the application component as a hexagonal cell. <br>The purpose was not to suggest that there would be six borders but to leave enough space to represent the different interfaces needed between the component and the external world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wS0bHFellWL2fUGZ.png" /><figcaption>Source: <a href="https://tsh.io/blog/hexagonal-architecture/">https://tsh.io/blog/hexagonal-architecture/</a></figcaption></figure><h3>In practice</h3><blockquote>I am purposely bypassing the tests here to be as concise as possible. You could find some help to unit test the architecture in <a href="https://medium.com/@odinnou/unit-testing-in-net-the-right-way-f8754836b605">my previous story</a>.</blockquote><h4>Domain</h4><p>Consider an existing solution composed of an empty ASP.NET Core project named “Service.csproj”.<br>Add a new class library project from the template list, name it “Domain.csproj” then remove the existing “Class1.cs” file.<br>Edit the existing “Service.csproj” file to add a reference to the new “Domain” project.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7014a949bc58832dec963476f761a833/href">https://medium.com/media/7014a949bc58832dec963476f761a833/href</a></iframe><blockquote>⚠️ You could also add the code of the Domain layer within the Service project (without a dedicated Domain project, I mean). But you should need to add some more tests to verify the isolation of layers.</blockquote><p>Then, add some business logic inside your Domain: a panda fetcher 🐼, an implementation of the <strong>IPandaFetcher </strong>interface (needed for the driving side), which uses an <strong>IPandaPersistencePort </strong>and an <strong>IReverseGeocodingPort </strong>(implemented on the driven side).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e3e8280da986e22156413fb4c7051eb/href">https://medium.com/media/3e3e8280da986e22156413fb4c7051eb/href</a></iframe><p>You could easily unit-test this part of your application by mocking <strong>IPandaPersistencePort </strong>and <strong>IReverseGeocodingPort</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*C1AbtkT_X_KTwpIZlXz3TA.png" /><figcaption><strong>Your “Domain” project should look like this.</strong></figcaption></figure><h4>Driving (or primary) side</h4><p>Now, we are going to build a REST API to expose panda data as JSON. Because it’s a trigger of our domain (it uses <strong>IPandaFetcher</strong>), it’s implemented in the driving side of the application.<br>The keyword “Controller” is dropped in favor of “Rest<strong>Adapter</strong>” to be consistent with the philosophy behind this architecture.</p><blockquote>Notice that Swagger integration, authentication scheme, and JWT readers should also be configured on the driving side. I tried to cover as many topics as possible without being confusing.</blockquote><p><a href="https://automapper.org/">AutoMapper</a> (or <a href="https://mapstruct.org/">MapStruct</a> for Java) is used to “convert” the domain model (<strong>Panda</strong>) to JSON format (<strong>PandaDto</strong>). It’s a great tool that requires some practice, but it is worth it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed5ed9b322f78a254978dfd943faa8fe/href">https://medium.com/media/ed5ed9b322f78a254978dfd943faa8fe/href</a></iframe><h4>Driven (or secondary) side</h4><p>The <strong>IPandaFetcher </strong>implementation requires two ports: IPandaPersistence<strong>Port</strong> and IReverseGeocoding<strong>Port</strong>. These interfaces are implemented on the driven side of the application as PandaPersistence<strong>Adapter</strong> and ReverseGeocoding<strong>Adapter</strong>.</p><p>The first is the database access layer (in our case, EF Core with the <a href="https://www.npgsql.org/">PostgreSQL provider</a>), and the second is an API call to a <a href="https://beeceptor.com/console/hexagonal-architecture-backup">mock reverse geocoding service</a>.</p><h4>Database access layer with EF Core.</h4><blockquote>I voluntarily highlighted only the access to the data, but the setup and the database migrations scripts are available on the <a href="https://github.com/odinnou/hexagonal-architecture-right-way">GitHub repository</a> (fully functional with DockerCompose).</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f077a7efcdeb075b4be95f15601020ee/href">https://medium.com/media/f077a7efcdeb075b4be95f15601020ee/href</a></iframe><h4>Reverse geocoding API call with <a href="https://restsharp.dev/">RestSharp</a>.</h4><blockquote>To speed up the writing of this story, I used <a href="https://beeceptor.com/">Beeceptor</a>, an online API mocking tool. I could have used <a href="https://www.mock-server.com/">MockServer</a> inside a Docker container, but the setup and expectations scripts are time-consuming.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4cb28bad1821a9dd38da50474ddb2f8/href">https://medium.com/media/f4cb28bad1821a9dd38da50474ddb2f8/href</a></iframe><h3>Conclusion</h3><p>I hope I have succeeded in demystifying this architecture proposal and helping you implement it in your application.</p><p>I advise using <a href="https://archunitnet.readthedocs.io/en/latest/">ArchUnitNET</a>: a “frame” for your software architecture. It can help your team, especially with junior developers. I explain its use in <a href="https://medium.com/@odinnou/unit-testing-in-net-the-right-way-f8754836b605">my previous story</a>.</p><p>You can access the entire source code of this story on <a href="https://github.com/odinnou/hexagonal-architecture-right-way">GitHub</a>, stay tuned!</p><h3>Edit #1</h3><p>Updated to .NET 7.0 !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df93bec46bff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit Testing in .NET: the right way]]></title>
            <link>https://medium.com/@odinnou/unit-testing-in-net-the-right-way-f8754836b605?source=rss-499cef748595------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8754836b605</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[software-craftsmanship]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Rémi Despelchin]]></dc:creator>
            <pubDate>Mon, 12 Sep 2022 19:48:50 GMT</pubDate>
            <atom:updated>2023-01-05T20:37:38.323Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wpm8a-3lCY74vZnP20T5AQ.png" /></figure><h3>Unit Testing in .NET: the right way</h3><p>🟩🟦🟦 <em>Beginner</em></p><blockquote>Disclaimer: this article is focused on the unit tests and not on a higher layer of the “<a href="https://semaphoreci.com/blog/testing-pyramid">Test Pyramid</a>”.</blockquote><h3>Choose your weapons</h3><p>The .NET ecosystem provides a <a href="https://nugetmusthaves.com/Category/Unit%20Testing">large number of testing libraries</a>.<br>In my humble opinion, there are five among them you need to know.</p><ul><li><a href="https://xunit.net/">xUnit</a>: the best test runner, compatible with all IDE and providing great flexibility across test use cases.</li><li><a href="https://github.com/moq/moq4">Moq</a>: a straightforward mocking library with good support of async/await.</li><li><a href="https://fluentassertions.com/">FluentAssertions</a>: a considerable time saving, 95% of your assertion needs are present in this package (to compare values, objects, or arrays).</li><li><a href="https://github.com/AutoFixture/AutoFixture">AutoFixture</a>: randomize everything! Improve your test reliability by avoiding the use of static test variables (aka. fixture).</li><li><a href="https://archunitnet.readthedocs.io/">ArchUnitNET</a>: a “frame” for your software architecture. It can be a great help, especially in a team with junior developers.</li></ul><h3>Warmup</h3><p>This is not an article on unit testing best practices (<a href="https://docs.microsoft.com/en-us/dotnet/core/testing/unit-testing-best-practices">there are already many of them</a>) but, if you have to remember only one thing: <strong>writing unit tests should not be a pain point</strong>.</p><p>Consider an existing solution composed of an empty “console app” project named Service.csproj.<br>Add to it a new “<a href="https://xunit.net/docs/getting-started/netfx/visual-studio">xUnit Test Project</a>” from the project template list, naming it “Tests.csproj”. (xUnit team offers setup for other IDE like Rider <a href="https://xunit.net/docs/getting-started/netfx/jetbrains-rider">here</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*ecwvl3qRSP7vYEfvs40U-g.png" /></figure><p>Edit Tests.csproj file to add a reference to the existing “Service” project and add the four missing packages (xUnit is already added).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b90f829444156d269cce72810030bab/href">https://medium.com/media/4b90f829444156d269cce72810030bab/href</a></iframe><p>Then, add some business logic inside your Service: a panda renamer 🐼.</p><blockquote>💢 <strong>WHAT?! That’s not TDD!<br></strong>Yeah, that’s irrelevant to the purpose of this article, but I intentionally left an interface unimplemented.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd1108ed93d6676ecb1b1aa779620c31/href">https://medium.com/media/fd1108ed93d6676ecb1b1aa779620c31/href</a></iframe><p>From this code, we could highlight two test cases.</p><ol><li>Providing an empty name to the Execute function, check if it threw an ArgumentNullException then verify if pandaFetcher has not been called.</li><li>Providing a valid name to the function, check if the new panda name is equal to the “newName” parameter.</li></ol><h3>Combine forces</h3><p>Now, we are ready to create our first unit test file named “PandaRenamerTest.cs” inside the “Tests” project.</p><p>We’ll use the power of these four packages (xUnit, FluentAssertions, Moq and AutoFixture) to reduce the code complexity and increase reliability.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d276837efc389a0cfdba5b14c9e290b1/href">https://medium.com/media/d276837efc389a0cfdba5b14c9e290b1/href</a></iframe><p>That’s all! Few lines of code, no fixture, and good readability.<br>From now on, I’m sure you’ll enjoy reaching the 80% code coverage.</p><h3>Hold on!</h3><p>You’ve reached 80% of code coverage, great! You could now invest some time to ensure that the architecture will be followed throughout the project.</p><p>ArchUnitNET was built for this purpose if you want to check that all of your use cases avoid using code from “Service.Mordor.*” namespace, you could!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26e0a617469d1c0f49219182e7d7bd77/href">https://medium.com/media/26e0a617469d1c0f49219182e7d7bd77/href</a></iframe><p>If, unfortunately, a developer uses some code from the “Service.Mordor.*” namespace inside a “Core” use case, the unit test will fail with a clear error message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ReDW95Ez615BDCP0Ajs6fw.png" /></figure><h3>Conclusion</h3><p>I regret to inform you that 80% code coverage is not enough 🙃, but it’s a good start! <br>Indeed, the next step is to check if your code works well in its entirety. <br>We’ll use integration tests to reach ~90% code coverage in the next chapter.</p><p>You can access the entire source code of this post on <a href="https://github.com/odinnou/testing-right-way">GitHub</a>, stay tuned!</p><h3>Edit #1</h3><p>As <a href="https://medium.com/u/ae1e6291afc3">xeladu</a> pointed out: “A code coverage metric of 80% or similar doesn’t indicate that your testing is good.” and he’s right.<br>You should test your tests with mutation testing to increase theirs reliability, <a href="https://stryker-mutator.io/">Stryker</a> is a great tool!</p><h3>Edit #2</h3><p>Updated to .NET 7.0 !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8754836b605" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>