DEV Community

Cover image for Azure Functions Integration Tests with Testcontainers and Azurite
Martin Oehlert
Martin Oehlert

Posted on AI-assisted

Azure Functions Integration Tests with Testcontainers and Azurite

Which bugs in a queue-triggered Azure Function can a test with a mocked QueueClient never catch? Every bug that lives in the storage service or in the trigger binding instead of in your code: the encoding of the queue message, a blob container that doesn't exist yet, the naming rules for containers and blobs, and the JSON the worker has to deserialize. A test against a real Azurite container catches all four. With one container for the whole test run, the sample's six tests, two of them through a running Functions host, finish in under ten seconds on my machine.

The unit testing article from earlier this year is the baseline: business logic in a service class, the function class tested with fakes, and a first look at Testcontainers. This series picks up where it stopped. Part 1 stays with Azure Storage, queues in and blobs out; the later parts cover Cosmos DB, Service Bus, architecture rules, contracts, load and CI. The code is in the companion repo, on .NET 10 with the isolated worker, xUnit v3 and Testcontainers 4.16. The repo moved to those versions after the unit testing article, so that article's code no longer matches it line for line.

The order pipeline under test

An API puts orders on the orders queue. A queue-triggered function picks each one up and, for a paid order, writes an invoice as JSON into the invoices blob container:

public sealed class OrderProcessor(BlobContainerClient invoices, ILogger<OrderProcessor> logger)
{
    [Function(nameof(OrderProcessor))]
    public async Task Run([QueueTrigger("orders")] Order order, CancellationToken cancellationToken)
    {
        if (order.Status != OrderStatus.Paid)
            return;

        await invoices.CreateIfNotExistsAsync(cancellationToken: cancellationToken);

        var invoice = new Invoice(order.Id, order.CustomerId, order.Total);
        await invoices.GetBlobClient($"order-{order.Id}.json")
            .UploadAsync(BinaryData.FromObjectAsJson(invoice), overwrite: true, cancellationToken);

        logger.LogInformation("Invoice written for order {OrderId}", order.Id);
    }
}
Enter fullscreen mode Exit fullscreen mode

The container client comes from DI, registered once in Program.cs against the same storage account the trigger uses:

builder.Services.AddSingleton(_ =>
    new BlobContainerClient(builder.Configuration["AzureWebJobsStorage"], "invoices"));
Enter fullscreen mode Exit fullscreen mode

The producer side is a small OrderApi class that serializes the order and sends it, plus an OrderQueue.Create factory for its QueueClient:

public static class OrderQueue
{
    // The queue trigger expects Base64; the SDK default (None) sends plain text that the trigger can't decode.
    public static QueueClient Create(string connectionString) =>
        new(connectionString, "orders", new QueueClientOptions { MessageEncoding = QueueMessageEncoding.Base64 });
}

public sealed class OrderApi(QueueClient queue)
{
    // The public API contract writes enums as names, like most ASP.NET Core APIs configured for JSON.
    private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web)
    {
        Converters = { new JsonStringEnumConverter() },
    };

    public Task PlaceAsync(Order order) => queue.SendMessageAsync(JsonSerializer.Serialize(order, Json));
}
Enter fullscreen mode Exit fullscreen mode

The unit tests most code bases have for this pipeline look like this, written with NSubstitute:

[Fact]
public async Task PlaceAsync_sends_the_order_to_the_queue()
{
    var queue = Substitute.For<QueueClient>();

    await new OrderApi(queue).PlaceAsync(PaidOrder);

#pragma warning disable xUnit1051 // Received() checks a recorded call; there is nothing to cancel
    await queue.Received().SendMessageAsync(Arg.Any<string>());
#pragma warning restore xUnit1051
}

[Fact]
public async Task Run_uploads_the_invoice()
{
    var invoices = Substitute.For<BlobContainerClient>();
    var blob = Substitute.For<BlobClient>();
    invoices.GetBlobClient(Arg.Any<string>()).Returns(blob);

    var processor = new OrderProcessor(invoices, NullLogger<OrderProcessor>.Instance);
    await processor.Run(PaidOrder, TestContext.Current.CancellationToken);

    await blob.Received().UploadAsync(Arg.Any<BinaryData>(), true, Arg.Any<CancellationToken>());
}
Enter fullscreen mode Exit fullscreen mode

(The pragma is for xUnit1051, a v3 analyzer that wants TestContext.Current.CancellationToken passed to every call that accepts a token. Received() only checks a call that already happened, so there is nothing to cancel.)

Both tests are green, and both stay green with every bug below put back into the code. A mock verifies that you called SendMessageAsync and UploadAsync. It can't tell you whether the message is readable by the trigger, or whether the upload would succeed.

Four bugs the mock passes

The queue message the trigger can't read

Remove the QueueClientOptions from OrderQueue.Create and you have the producer most people write first:

new QueueClient(connectionString, "orders");
Enter fullscreen mode Exit fullscreen mode

It compiles, it sends, and SendMessageAsync returns a receipt. The queue trigger documentation says "Functions expect a base64 encoded string", and the MessageEncoding option of the v12 SDK says "The default is None". So the client puts the JSON on the queue as plain text, the trigger fails to decode it on every attempt, and after five attempts (the default maxDequeueCount) the host moves it to orders-poison. The log line you get is about the dequeue count, along the lines of "Message has reached MaxDequeueCount of 5. Moving message to queue 'orders-poison'" (azure-sdk-for-net #21449), not about the encoding. No exception reaches the producer, and nothing in the function's own code runs, so there is nothing for its logs to say.

The mocked QueueClient in PlaceAsync_sends_the_order_to_the_queue records the call and passes. It never encodes anything, and no trigger reads from it.

There are two fixes. Set MessageEncoding = QueueMessageEncoding.Base64 on every producer, as OrderQueue.Create does, or tell the Functions host to accept plain text with "messageEncoding": "none" under extensions.queues in host.json (valid values are base64 and none; the isolated worker needs version 5.x or later of the Storage Queues extension). The host setting fixes it for every producer at once, including ones in other languages, but it also changes what the trigger expects from producers that already send Base64. In a code base where one team owns both sides, keep the default and fix the client in one shared factory.

Only a test that runs the trigger catches this bug. Calling OrderProcessor.Run directly hands it an Order object, which skips the decoding, so this one needs the round trip through func start further down.

The container that Bicep created

The second bug is the one line in Run that looks optional: CreateIfNotExistsAsync. Without it, the function uploads into a container it assumes exists. In production it does, because the Bicep template created it. In a new environment, a renamed container, or a storage account someone recreated, the upload fails with 404 ContainerNotFound ("The specified container does not exist."), and every paid order retries into the poison queue.

The mocked BlobContainerClient has no idea which containers exist, so Run_uploads_the_invoice passes either way. Whether to create the container in code or keep it in infrastructure is a real choice: CreateIfNotExistsAsync costs a request per message, and with a locked-down identity the function may not have permission to create containers at all. Either way the test that catches the missing container has to run against storage that starts empty.

Names: lowercase containers, case-sensitive blobs

Azure Storage has two casing rules, and a mock enforces neither. From the naming reference: "All letters in a container name must be lowercase", and "Blob names are case-sensitive".

The first one bites when someone writes "Invoices" in the Program.cs registration. The service rejects it with a 400 and the error code InvalidResourceName. Azurite checks the same pattern on every request.

The second one is quieter. If the function writes Order-42.json and the service that serves invoices asks for order-42.json, the upload succeeds and the read gets a 404. Both sides look correct on their own, and both sides' unit tests pass.

The enum that arrives as a string

The isolated worker deserializes the queue message with System.Text.Json, and the serialization docs are clear about enums: "By default, enums are serialized as numbers." OrderApi follows its public JSON contract and writes "status":"Paid". A worker that expects a number can't bind that to OrderStatus, the function never runs, and the message retries into the poison queue. The fix sits on the enum, so every serializer that touches the type agrees:

public record Order(string Id, string CustomerId, decimal Total, OrderStatus Status);

// Producers send the name ("Paid"); System.Text.Json reads enums as numbers unless told otherwise.
[JsonConverter(typeof(JsonStringEnumConverter<OrderStatus>))]
public enum OrderStatus
{
    Pending,
    Paid,
}
Enter fullscreen mode Exit fullscreen mode

One serialization difference that is not a bug: property name casing. OrderApi writes camelCase ("customerId") and the record has CustomerId. The worker's defaults ignore casing on property names, so this binds fine, and the round-trip test below proves it on every run.

The mocked test calls Run with an Order object, so nothing gets serialized and the enum never meets a string.

Two of the four bugs live in the storage service, two in the binding. The container and the blob names fail on the first real request, so calling OrderProcessor.Run with a real BlobContainerClient is enough to catch them. The encoding and the enum fail before Run is ever called, inside the host and the worker, so only a test that puts a message on a real queue and lets the Functions host pick it up will see them.

Azurite in a container, per test run

The test project needs xUnit v3, the Azurite module and the runner packages. With central package management the versions live in Directory.Packages.props, and the test project only names them:

<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="NSubstitute" />
<PackageReference Include="Testcontainers.Azurite" />
<PackageReference Include="xunit.v3" />
<PackageReference Include="xunit.runner.visualstudio">
  <PrivateAssets>all</PrivateAssets>
  <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
Enter fullscreen mode Exit fullscreen mode

The sample pins Testcontainers.Azurite 4.16.0, xunit.v3 4.0.3 and xunit.runner.visualstudio 4.0.1. An xUnit v3 test project is an executable, so it also sets <OutputType>Exe</OutputType>. On the .NET 10 SDK, dotnet test no longer runs these projects through the VSTest target; it stops with "Testing with VSTest target is no longer supported by Microsoft.Testing.Platform on .NET 10 SDK and later". The repo opts into the new test runner in global.json:

"test": {
  "runner": "Microsoft.Testing.Platform"
}
Enter fullscreen mode Exit fullscreen mode

After that, a single project runs with dotnet test --project OrderPipelineDemo.Tests.

The container itself takes four lines:

private readonly AzuriteContainer _azurite =
    new AzuriteBuilder("mcr.microsoft.com/azure-storage/azurite:3.37.0")
        .WithInMemoryPersistence()
        // Azure.Storage.Blobs 12.30 and Queues 12.28 send API version 2026-10-06; Azurite 3.37.0 stops at 2026-06-06.
        .WithCommand("--skipApiVersionCheck")
        .Build();
Enter fullscreen mode Exit fullscreen mode

Pin the image in the constructor. In Testcontainers 4.16 the parameterless new AzuriteBuilder() is marked obsolete ("Use the constructor with the image parameter instead"), and its default is still azurite:3.28.0. With TreatWarningsAsErrors the obsolete constructor doesn't even compile. Even without that setting, 3.28.0 is the image the unit testing article ran into: Core Tools sent a storage service version it didn't know.

Pinning the newest image isn't enough either. 3.37.0 is the latest Azurite release, and it supports service versions up to 2026-06-06. The current storage SDKs are already past that: the first run of the sample failed with "The API version 2026-10-06 is not supported by Azurite. Please upgrade Azurite to latest version and retry." There is no newer Azurite to upgrade to, so the sample passes --skipApiVersionCheck, a flag Azurite has for this case (the AZURITE_SKIP_API_VERSION_CHECK=true environment variable does the same). The alternative is to pin each client to an older service version through its options, which you would then have to do in the function code as well. The gotchas below cover when the flag can go.

WithInMemoryPersistence() keeps the blobs and queues in memory instead of on the container's disk; nothing outlives the test run anyway. The builder maps Azurite's three ports (10000 to 10002) to random host ports, so two test runs on the same CI agent don't collide, and GetConnectionString() returns a connection string with those mapped ports filled in. Pass it straight to BlobContainerClient, QueueClient or the Functions host.

One container, many tests: xUnit v3 fixtures

Test project, Testcontainers, Azurite container and the function code

Starting a container takes seconds, and the tests themselves take milliseconds, so the real decision is how many containers you start. xUnit v3 gives you three places to put one:

  • A class fixture (IClassFixture<T>) is created once per test class. Every class that touches storage pays for its own container.
  • A collection fixture is shared by every class in a [Collection]. One container, but "tests within a single test collection will not be run in parallel against each other" (xUnit docs), so you trade the container cost for parallelism.
  • An assembly fixture, new in v3, is created once for the whole test assembly and shared by every test, with parallelism left as it is.

The sample uses the assembly fixture:

[assembly: AssemblyFixture(typeof(AzuriteFixture))]

namespace OrderPipelineDemo.Tests;

public sealed class AzuriteFixture : IAsyncLifetime
{
    private readonly AzuriteContainer _azurite =
        new AzuriteBuilder("mcr.microsoft.com/azure-storage/azurite:3.37.0")
            .WithInMemoryPersistence()
            // Azure.Storage.Blobs 12.30 and Queues 12.28 send API version 2026-10-06; Azurite 3.37.0 stops at 2026-06-06.
            .WithCommand("--skipApiVersionCheck")
            .Build();

    public string GetConnectionString() => _azurite.GetConnectionString();

    // Lowercase hex, so it's valid for queue and container names.
    public static string UniqueName(string prefix) => $"{prefix}-{Guid.NewGuid():N}";

    public async ValueTask InitializeAsync() => await _azurite.StartAsync();

    public async ValueTask DisposeAsync() => await _azurite.DisposeAsync();
}
Enter fullscreen mode Exit fullscreen mode

If you are coming from xUnit 2, two things changed in IAsyncLifetime: InitializeAsync and DisposeAsync return ValueTask instead of Task, and the interface now inherits IAsyncDisposable. A class that implements it without being sealed gets CA1816 from the .NET analyzers, which wants GC.SuppressFinalize in DisposeAsync; sealing the fixture is the shorter fix.

A test class asks for the fixture in its constructor, the same way it would ask for a class fixture:

public class OrderProcessorStorageTests(AzuriteFixture azurite)
Enter fullscreen mode Exit fullscreen mode

One shared container means the isolation between tests has to come from the data. A storage test that needs its own blob container gets a name from UniqueName, such as invoices-3f2a9c.... Guid.ToString("N") is 32 lowercase hex characters, so the name passes the lowercase rule from bug three and stays well under the 63-character limit. The round-trip tests can't do that, because the queue name is fixed in the trigger attribute; they share orders and invoices and stay apart through a unique order ID per test. Nothing gets cleaned up between tests, because the container is gone at the end of the run.

The round-trip test needs a second fixture on top: the Functions host. In v3 a class fixture can take assembly and collection fixtures as constructor parameters, so FuncHostFixture(AzuriteFixture azurite) points func start at the same Azurite instance the tests write to. That fixture and the test that uses it are the next two sections.

Testing the function class against real storage

The fast half of the suite skips the host entirely. It builds OrderProcessor by hand, with a real BlobContainerClient pointed at Azurite, and calls Run:

public class OrderProcessorStorageTests(AzuriteFixture azurite)
{
    private static readonly Order PaidOrder = new("A-42", "c-7", 99.50m, OrderStatus.Paid);

    [Fact]
    public async Task Run_writes_the_invoice_into_a_container_that_does_not_exist_yet()
    {
        var ct = TestContext.Current.CancellationToken;
        var invoices = new BlobContainerClient(
            azurite.GetConnectionString(), AzuriteFixture.UniqueName("invoices"));
        var processor = new OrderProcessor(invoices, NullLogger<OrderProcessor>.Instance);

        await processor.Run(PaidOrder, ct);

        var blob = await invoices.GetBlobClient("order-A-42.json").DownloadContentAsync(ct);
        Assert.Equal(99.50m, blob.Value.Content.ToObjectFromJson<Invoice>()!.Amount);
    }

    [Fact]
    public async Task Run_fails_on_an_uppercase_container_name()
    {
        var invoices = new BlobContainerClient(azurite.GetConnectionString(), "Invoices");
        var processor = new OrderProcessor(invoices, NullLogger<OrderProcessor>.Instance);

        var error = await Assert.ThrowsAsync<RequestFailedException>(
            () => processor.Run(PaidOrder, TestContext.Current.CancellationToken));

        Assert.Equal("InvalidResourceName", error.ErrorCode);
    }
}
Enter fullscreen mode Exit fullscreen mode

The first test is the one that matters day to day. The container name is new for every run, so the storage starts out without it, like a fresh environment. Delete CreateIfNotExistsAsync from Run and the test fails with ContainerNotFound. Change the blob name to Order-{order.Id}.json and the upload succeeds, but DownloadContentAsync("order-A-42.json") gets a 404. The test reads the blob back under the name its consumer uses, which is the only way to catch the casing half of bug three. Reading the amount back also proves the invoice is valid JSON in the shape the reader expects.

The second test pins the container rule. It asserts on ErrorCode, not on the exception message, for a reason that comes up again in the gotchas: Azurite's status codes and error codes match Azure Storage, its messages don't always.

Both tests take milliseconds once the container is up. What they can't see is everything before Run: they hand the method a finished Order, so the Base64 decoding and the enum binding never happen. Bugs one and four stay green here.

The full round trip: enqueue, wait for the blob

To get the trigger and the worker into the test, the test has to run the Functions host. There is no in-process test host for the isolated worker; the request for a TestServer-style host (azure-functions-dotnet-worker #1196) was closed as not planned. So the fixture starts func start as a child process, the same way the unit testing article did for an HTTP function. Trimmed to the parts that matter:

public sealed class FuncHostFixture(AzuriteFixture azurite) : IAsyncLifetime
{
    private Process? _func;

    public async ValueTask InitializeAsync()
    {
        if (!CoreToolsInstalled)
            return;

        await new QueueClient(azurite.GetConnectionString(), "orders").CreateIfNotExistsAsync();

        var startInfo = new ProcessStartInfo("func", $"start --port {FreeTcpPort()}")
        {
            WorkingDirectory = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../../OrderPipelineDemo")),
            RedirectStandardOutput = true,
            UseShellExecute = false,
        };
        startInfo.Environment["AzureWebJobsStorage"] = azurite.GetConnectionString();
        startInfo.Environment["FUNCTIONS_WORKER_RUNTIME"] = "dotnet-isolated";

        var ready = new TaskCompletionSource();
        _func = Process.Start(startInfo)!;
        _func.OutputDataReceived += (_, e) =>
        {
            if (e.Data?.Contains("Worker process started and initialized", StringComparison.Ordinal) == true)
                ready.TrySetResult();
        };
        _func.BeginOutputReadLine();

        // func start builds the app first, so allow for a cold build.
        await ready.Task.WaitAsync(TimeSpan.FromSeconds(90));
    }

    public ValueTask DisposeAsync()
    {
        _func?.Kill(entireProcessTree: true);
        _func?.Dispose();
        return ValueTask.CompletedTask;
    }
}
Enter fullscreen mode Exit fullscreen mode

Three details in that fixture matter. AzureWebJobsStorage is set on the process, so the host and the BlobContainerClient registered in Program.cs both talk to the test's Azurite container instead of whatever local.settings.json says. The fixture waits for the line "Worker process started and initialized" on stdout, because a host that has started but has no worker yet would leave the first message sitting on the queue. And DisposeAsync kills the whole process tree: func starts the worker as a separate process, and killing only the parent leaves a .NET process running after the tests finish.

The test itself is short:

public class OrderRoundTripTests(AzuriteFixture azurite) : IClassFixture<FuncHostFixture>
{
    private const string NoCoreTools = "Azure Functions Core Tools (func) is not on PATH";

    [Fact]
    public async Task Placed_order_comes_out_as_an_invoice_blob()
    {
        Assert.SkipUnless(FuncHostFixture.CoreToolsInstalled, NoCoreTools);
        var ct = TestContext.Current.CancellationToken;
        var order = new Order(Guid.NewGuid().ToString("N"), "c-7", 99.50m, OrderStatus.Paid);
        var invoices = new BlobContainerClient(azurite.GetConnectionString(), "invoices");

        var queue = OrderQueue.Create(azurite.GetConnectionString());
        await new OrderApi(queue).PlaceAsync(order);

        var invoice = invoices.GetBlobClient($"order-{order.Id}.json");
        await WaitUntilAsync(() => invoice.ExistsAsync(ct), TimeSpan.FromSeconds(30));
    }
Enter fullscreen mode Exit fullscreen mode

OrderQueue.Create and OrderApi are the classes the API uses, not test doubles, so the message on the queue has the encoding and the JSON that production sends. Take the Base64 option out of OrderQueue.Create, or the converter off OrderStatus, and this test fails with a TimeoutException after 30 seconds. Put them back and it passes well inside the deadline.

There is no Task.Delay(5000) followed by an assert. The host polls the queue on its own schedule, and in local development that interval backs off to at most two seconds (queue trigger docs), so a fixed sleep is either too short on a slow agent or wastes time on a fast one. WaitUntilAsync checks every 250 ms and gives up at a deadline:

public static class Poll
{
    public static Task WaitUntilAsync(Func<Task<Response<bool>>> condition, TimeSpan timeout) =>
        WaitUntilAsync(async () => (bool)await condition(), timeout);

    public static async Task WaitUntilAsync(Func<Task<bool>> condition, TimeSpan timeout)
    {
        var deadline = DateTime.UtcNow + timeout;
        while (!await condition())
        {
            if (DateTime.UtcNow > deadline)
                throw new TimeoutException($"Condition not met within {timeout}.");

            await Task.Delay(TimeSpan.FromMilliseconds(250), TestContext.Current.CancellationToken);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

The first overload exists because ExistsAsync returns Response<bool>, which converts to bool but doesn't fit a Func<Task<bool>>. The delay takes the test's cancellation token, so a cancelled run stops polling right away instead of sitting out the 30 seconds.

The second round-trip test proves the failure path instead of assuming it. It sends the same order with a plain QueueClient, the SDK default, and waits for it in the poison queue:

    [Fact]
    public async Task Plain_text_message_ends_up_in_the_poison_queue()
    {
        Assert.SkipUnless(FuncHostFixture.CoreToolsInstalled, NoCoreTools);
        var ct = TestContext.Current.CancellationToken;
        var order = new Order(Guid.NewGuid().ToString("N"), "c-7", 99.50m, OrderStatus.Paid);
        var poison = new QueueClient(azurite.GetConnectionString(), "orders-poison");
        await poison.CreateIfNotExistsAsync(cancellationToken: ct);

        // The SDK default: MessageEncoding.None, so the trigger receives plain text.
        var plainText = new QueueClient(azurite.GetConnectionString(), "orders");
        await new OrderApi(plainText).PlaceAsync(order);

        await WaitUntilAsync(
            async () => (await poison.PeekMessagesAsync(32, ct)).Value.Any(m => m.Body.ToString().Contains(order.Id, StringComparison.Ordinal)),
            TimeSpan.FromSeconds(60));
    }
}
Enter fullscreen mode Exit fullscreen mode

Locally, the message reaches orders-poison in well under a second; the 60-second deadline is headroom for a slow CI agent. The test pins down the behaviour from bug one, and it turns red the day someone sets "messageEncoding": "none" in host.json, and that is the day every Base64 producer needs a second look.

Both round-trip tests start with Assert.SkipUnless, the dynamic skip that is new in xUnit v3. Without Core Tools on the PATH, the fixture does nothing, the two tests show up as skipped with the reason, and the other four still run. A contributor without func gets a green run with two visible skips instead of a 90-second timeout.

Gotchas

Startup time is the container, not the tests. The whole run, six tests including both trips through func start, takes about seven seconds on my machine with the image already pulled and the function app already built. The first run on a new machine pays for the image pull, and the first func start builds the function app, which is why the fixture allows 90 seconds before it gives up. On a CI agent every run is a first run unless you cache.

One assembly fixture, but the host is per class. AzuriteFixture is created once for the assembly. FuncHostFixture is a class fixture, so if the round-trip tests get split across two classes, two func processes start against the same orders queue. Each message then goes to whichever host polls first. The tests still pass, since they look for their own order ID, but you pay for a second host start and lose any clue which host processed what. Keep the round-trip tests in one class, or move the host to an assembly fixture too. Inside that one class, xUnit runs the tests one after another (a class is its own test collection by default), which is what you want when two tests share one queue and one host.

Ports. Azurite's ports are random, but the func host needs one too, and its default is 7071, the same port the func start in your other terminal is probably using. FreeTcpPort asks the OS for an unused one. There is a small window between releasing that port and func binding it; I've never hit it, but it is a race, not a guarantee.

The API version check comes back with every SDK update. The --skipApiVersionCheck flag from earlier hides a real mismatch: the SDK speaks a newer storage service version than Azurite knows. Today that's harmless for blobs and queues. To find out when the flag can go, remove it after each Azurite release and run the suite; if the tests pass without it, Azurite has caught up.

What Azurite doesn't emulate. The Azurite docs list the differences. Three matter for tests like these:

  • Only Blob, Queue and Table. Azure Files and Data Lake Storage Gen2 aren't there.
  • No scale or performance. Azurite "doesn't support large numbers of connected clients" and gives "no performance guarantee", so throttling and timeouts under load are Part 5's job, not this suite's.
  • Error messages can differ while status codes match, which is why the uppercase test checks ErrorCode.

The tests also authenticate with the emulator's well-known account key. A function that uses a managed identity in production has role assignments that no test here ever checks; the locked-down identity from bug two that can't create containers only shows up in a deployed environment.

Colima and other non-default Docker sockets. On a Mac with Colima, DOCKER_HOST points at a socket under your home folder. Testcontainers starts its cleanup container, Ryuk, with that path mounted, and Docker inside the Colima VM can't find it: the run fails with "invalid mount config for type bind". Setting TESTCONTAINERS_DOCKER_SOCKET_OVERRIDE=/var/run/docker.sock tells Testcontainers the socket path inside the VM, and the run goes through. Docker Desktop and the CI runners don't need it.

Running it in CI

GitHub Actions ubuntu-latest runners ship with Docker, so the Azurite tests run there with no extra setup: Testcontainers finds the daemon, pulls the image and maps the ports. The round-trip tests are the ones with a decision attached, because the runner has no Core Tools.

The companion repo installs them in the job, so all six tests run. This is the whole workflow, orderpipeline-tests.yml:

name: OrderPipelineDemo tests

on:
  push:
    paths:
      - 'OrderPipelineDemo/**'
      - 'OrderPipelineDemo.Tests/**'
      - 'Directory.Build.props'
      - 'Directory.Packages.props'
      - 'global.json'
      - '.github/workflows/orderpipeline-tests.yml'
  pull_request:
    paths:
      - 'OrderPipelineDemo/**'
      - 'OrderPipelineDemo.Tests/**'
      - 'Directory.Build.props'
      - 'Directory.Packages.props'
      - 'global.json'
      - '.github/workflows/orderpipeline-tests.yml'
  workflow_dispatch:

permissions:
  contents: read

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7

      - uses: actions/setup-dotnet@v6
        with:
          global-json-file: global.json

      # Without Core Tools the two func start round-trip tests skip instead of running.
      - run: npm install -g azure-functions-core-tools@4 --unsafe-perm true

      - run: dotnet test --project OrderPipelineDemo.Tests
Enter fullscreen mode Exit fullscreen mode

The paths filter keeps it from running on changes to the other samples in the repo, but it still fires when the shared build files change, since a package bump in Directory.Packages.props is the kind of change these tests exist for.

Leave the Core Tools step out and Assert.SkipUnless reports the two round-trip tests as skipped and the four storage tests still guard the container and naming bugs. That is a reasonable trade for a pull request build, as long as some pipeline runs the round trip before a release, because the skipped tests are the only ones that catch the encoding and the enum.

Two more points before this goes into a real pipeline. dotnet test only works here because global.json selects Microsoft.Testing.Platform; a runner with an older SDK than the one in global.json fails before any test runs, which setup-dotnet with global-json-file prevents. And the sample keeps the mocked tests in the same project as the container tests for brevity. In a real code base, put the Docker-dependent tests in their own project, so the unit tests still run on a machine without Docker.

Caching the Azurite image between runs, splitting slow tests from fast ones, and dealing with the flaky test that a shared queue eventually produces are Part 6 of this series, "Tests in CI".

Conclusion

Each of the four bugs sits at a boundary the code under test doesn't own. The SDK's default encoding, the trigger's expectations, the storage naming rules and the worker's JSON settings are all decided somewhere else, and a mock replaces exactly that somewhere else with something that agrees with you. Mocks stay the right tool for the logic in your own classes. For the contract with the storage service and the Functions host, a container that starts once per test run costs a few seconds and answers questions a mock can't.

If you only add one test from this article, add the round trip. The storage tests catch two bugs that also fail loudly in the first deployment; the round trip catches the two that fail quietly, with a full poison queue and a log line about dequeue counts.

Part 2 does the same for Cosmos DB and Service Bus, where the emulators are heavier, slower to start and further from the real service than Azurite.

Does your test suite ever put a real message on a real queue, or does every queue in it come from Substitute.For?

Top comments (0)