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); } } 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")); 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)); } 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>()); } (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"); 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, } 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> 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" } 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(); 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
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(); } 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) 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); } } 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; } } 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 th...



