Why did the order pipeline's tests stay green while production rejected orders and shipped one of them twice? Both failures came from rules that the services enforce and the fakes never heard of: Cosmos DB refuses a write whose partition key doesn't match the document, and Service Bus takes a message lock back when the handler holds it longer than the lock lasts. The in-memory repository is a Dictionary without partitions and the mocked ServiceBusSender has no lock to lose, so no test against them can go red for either bug. The Cosmos DB and Service Bus emulators, started by Testcontainers, reproduce both, and with the images cached they are ready in about 15 seconds.
Testing .NET on Azure: Beyond Unit Tests (6-part series)
- Part 1: Azure Functions Integration Tests with Testcontainers and Azurite
- Part 2: Cosmos DB and Service Bus Emulators in Testcontainers for .NET (you are here)
- Part 3: Architecture Tests with ArchUnitNET (coming next week)
- Part 4: API Contract Tests (coming soon)
- Part 5: Load Testing with k6 and Azure Load Testing (coming soon)
- Part 6: Tests in CI: Flaky Tests, Parallelism and Coverage Gates (coming soon)
Part 1 tested the same OrderPipelineDemo against Azurite: orders come in on a storage queue, invoices go out as blobs. This part adds a Cosmos DB repository for the orders and a Service Bus queue for shipping. The code is in the companion repo, still on .NET 10 with the isolated worker and xUnit v3, now with Testcontainers 4.17.0 and its Cosmos DB and Service Bus modules.
The order pipeline grows two dependencies
Paid orders are stored in a Cosmos DB container called orders, partitioned by customer:
public sealed class CosmosOrderRepository(Container orders) : IOrderRepository
{
public const string DatabaseName = "shop";
public const string ContainerName = "orders";
public const string PartitionKeyPath = "/customerId";
// Web defaults write "id" and "customerId": the property Cosmos requires and the one the key path names.
public static CosmosClientOptions ClientOptions() => new()
{
UseSystemTextJsonSerializerWithOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web),
};
public Task SaveAsync(Order order, CancellationToken cancellationToken) =>
orders.UpsertItemAsync(order, new PartitionKey(order.CustomerId), cancellationToken: cancellationToken);
public async Task<Order?> GetAsync(string id, string customerId, CancellationToken cancellationToken)
{
try
{
var response = await orders.ReadItemAsync<Order>(
id, new PartitionKey(customerId), cancellationToken: cancellationToken);
return response.Resource;
}
catch (CosmosException e) when (e.StatusCode == HttpStatusCode.NotFound)
{
return null;
}
}
}
PartitionKeyPath is the key path the production container was created with, and the test fixture creates its container from the same constant, so the two can't drift apart. ClientOptions switches the SDK to System.Text.Json with web defaults. That matters twice: Cosmos DB requires a lowercase id property on every item, and the key path /customerId names a property that has to exist with exactly that casing. The SDK's default serializer would write Id and CustomerId. The project still references Newtonsoft.Json, which the SDK needs internally even with System.Text.Json configured. GetAsync turns a 404 into null, which is the contract the rest of the pipeline expects from "order not found".
Shipping runs on Service Bus. Once an order is paid, a message goes to the order-paid queue, with the order id as the message id:
public sealed class ShippingRequests(ServiceBusSender sender)
{
public const string QueueName = "order-paid";
public Task RequestAsync(Order order, CancellationToken cancellationToken) =>
sender.SendMessageAsync(
new ServiceBusMessage(BinaryData.FromObjectAsJson(order)) { MessageId = order.Id }, cancellationToken);
}
A worker picks the message up, books the carrier, and only then completes the message:
public sealed class ShipmentHandler(ICarrier carrier)
{
// Same knob as maxAutoLockRenewalDuration in host.json for the Functions trigger: it has to outlast
// the slowest carrier call, or the lock expires while the booking is still running.
public static ServiceBusProcessorOptions ProcessorOptions(TimeSpan maxAutoLockRenewal) => new()
{
AutoCompleteMessages = false,
MaxConcurrentCalls = 1,
MaxAutoLockRenewalDuration = maxAutoLockRenewal,
};
public Task ShipAsync(ServiceBusReceivedMessage message, CancellationToken cancellationToken) =>
carrier.BookAsync(message.Body.ToObjectFromJson<Order>()!, cancellationToken);
public async Task HandleAsync(ProcessMessageEventArgs args)
{
await ShipAsync(args.Message, args.CancellationToken);
await args.CompleteMessageAsync(args.Message, args.CancellationToken);
}
}
ShipAsync reads the order from the message and books the carrier. HandleAsync wraps it for a ServiceBusProcessor, the SDK's receive loop, which also renews the message lock in the background for up to MaxAutoLockRenewalDuration. Settlement there is manual (AutoCompleteMessages = false), so a booking that throws never completes the message. In production, a Service Bus triggered function calls ShipAsync and leaves receiving, renewing and completing to the Functions host. The tests drive HandleAsync through the processor so they control the renewal window; the trigger section explains why.
The existing tests use a fake and two mocks. The fake repository is a dictionary keyed by order id:
public sealed class InMemoryOrderRepository : IOrderRepository
{
private readonly Dictionary<string, Order> _orders = [];
public Task SaveAsync(Order order, CancellationToken cancellationToken)
{
_orders[order.Id] = order;
return Task.CompletedTask;
}
public Task<Order?> GetAsync(string id, string customerId, CancellationToken cancellationToken) =>
Task.FromResult(_orders.GetValueOrDefault(id));
}
The handler test mocks the receiver that ProcessMessageEventArgs settles through, and checks that the carrier was booked and the message completed:
[Fact]
public async Task HandleAsync_books_the_carrier_and_completes_the_message()
{
var carrier = Substitute.For<ICarrier>();
var receiver = Substitute.For<ServiceBusReceiver>();
var message = ServiceBusModelFactory.ServiceBusReceivedMessage(body: BinaryData.FromObjectAsJson(PaidOrder));
var args = new ProcessMessageEventArgs(message, receiver, TestContext.Current.CancellationToken);
await new ShipmentHandler(carrier).HandleAsync(args);
await carrier.Received(1).BookAsync(PaidOrder, Arg.Any<CancellationToken>());
await receiver.Received().CompleteMessageAsync(message, Arg.Any<CancellationToken>());
}
Together with a round trip through InMemoryOrderRepository and a mocked ServiceBusSender for ShippingRequests, that makes three green tests. They stay green with both production bugs in the code.
Two bugs the fakes agree with
The partition key the container never had
The first version of SaveAsync passed the order id as the partition key:
orders.UpsertItemAsync(order, new PartitionKey(order.Id), cancellationToken: cancellationToken);
It reads naturally, since the id is the thing you look orders up by. Cosmos DB doesn't accept it. It extracts the partition key from the document itself (the value at /customerId, here c-7) and compares it with the one in the request. When they differ, the write fails with 400 BadRequest and the message "PartitionKey extracted from document doesn't match the one specified in the header" (troubleshooting page). Every paid order failed to save.
The read side has a quieter version of the same mistake. A caller that only has the order id passes it twice, GetAsync(order.Id, order.Id), and Cosmos DB looks for the item in a partition where it doesn't exist. That's a 404, GetAsync returns null, and the caller concludes that the order was never stored. No exception, no log line about partition keys.
InMemoryOrderRepository passes both. The dictionary has no partitions, SaveAsync ignores where the key comes from, and GetAsync ignores customerId altogether.
The lock that ran out mid-shipment
Service Bus delivers a message in peek-lock mode: the receiver gets the message plus a lock, and nobody else sees the message until the lock expires or the receiver settles it (locks and settlement). The lock lasts LockDuration, one minute by default and five at most. ShipmentHandler books first and completes second. When the carrier API takes longer than the lock and nothing renews it, CompleteMessageAsync throws a ServiceBusException with Reason = MessageLockLost. By then the message is back on the queue, the next receive gets it with DeliveryCount = 2, and the carrier gets a second booking for the same order.
The mocked receiver can't produce any of that. CompleteMessageAsync on a substitute returns a completed task, and there is no clock in the mock for a lock to expire against.
Where does this bite in Azure Functions? The Service Bus trigger renews the lock while your function runs, up to maxAutoLockRenewalDuration (five minutes by default), and completes the message when the function returns (PeekLock behavior). A function loses its lock only when the work outlives that window; a worker on ServiceBusReceiver has no renewal unless you write it. The tests use MaxAutoLockRenewalDuration = TimeSpan.Zero for "nothing renews the lock", and a five second LockDuration keeps them at seconds.
Running the Cosmos DB emulator in Testcontainers
The test project references the two new modules next to the Azurite one from Part 1:
<PackageReference Include="Testcontainers.CosmosDb" />
<PackageReference Include="Testcontainers.ServiceBus" />
Both are at 4.17.0 in Directory.Packages.props. The Cosmos DB container is one line:
private readonly CosmosDbContainer _cosmos =
new CosmosDbBuilder("mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:vnext-EN20261123").Build();
The image is the Linux vNext emulator. Pin the dated tag: vnext-latest moves, and on the day I wrote this it pointed at the same digest as vnext-EN20261123. The image is multi-arch, so it runs natively on Apple silicon. In 4.17 the parameterless CosmosDbBuilder() is marked obsolete; the image goes into the constructor. The module waits for the emulator's Started log line, which took about three seconds here once the image was pulled.
The client needs one setting that production doesn't:
var options = CosmosOrderRepository.ClientOptions();
// The vNext emulator only serves gateway mode; the SDK's default (direct) fails on the first call.
options.ConnectionMode = ConnectionMode.Gateway;
_cosmosClient = new CosmosClient(_cosmos.GetConnectionString(), options);
Database database = await _cosmosClient.CreateDatabaseIfNotExistsAsync(CosmosOrderRepository.DatabaseName);
Orders = await database.CreateContainerIfNotExistsAsync(
CosmosOrderRepository.ContainerName, CosmosOrderRepository.PartitionKeyPath);
The vNext emulator only implements gateway mode, and the module runs it over plain HTTP. Microsoft Learn says the .NET SDK doesn't support the emulator's HTTP mode and shows --protocol https with a trusted certificate instead (emulator docs). With SDK 3.64.0 and this tag, HTTP worked as long as the client was in gateway mode. Without that line the SDK defaults to direct mode, and the first call (CreateDatabaseIfNotExistsAsync) fails with 400 BadRequest.
The module also exposes container.HttpClient, which rewrites every request to the mapped host port. It exists for emulators that advertise their in-container port 8081, which the SDK would then try to reach on your machine. This vNext tag advertises localhost with the mapped port instead, so the sample leaves it out. If a later tag goes back to 8081, options.HttpClientFactory = () => _cosmos.HttpClient; is the fix.
The database and container come from the same constants as production, with the real key path. Every test then gets its own order id, so all of them can share the one container:
[Fact]
public async Task A_write_with_the_order_id_as_partition_key_is_rejected()
{
var order = NewPaidOrder();
var error = await Assert.ThrowsAsync<CosmosException>(() => emulators.Orders.UpsertItemAsync(
order, new PartitionKey(order.Id), cancellationToken: TestContext.Current.CancellationToken));
Assert.Equal(HttpStatusCode.BadRequest, error.StatusCode);
}
[Fact]
public async Task A_read_with_the_order_id_as_partition_key_finds_nothing()
{
var ct = TestContext.Current.CancellationToken;
var repository = new CosmosOrderRepository(emulators.Orders);
var order = NewPaidOrder();
await repository.SaveAsync(order, ct);
Assert.Null(await repository.GetAsync(order.Id, order.Id, ct));
}
The first test is the loud bug, written against the container directly because the repository no longer contains it. The second is the quiet one through the repository. Both run in milliseconds once the emulator is up. Next to them, SaveAsync_then_GetAsync_returns_the_order saves through CosmosOrderRepository and reads the order back, which is also the test that catches a serializer writing Id instead of id.
The Service Bus emulator in Testcontainers needs a second container
The Service Bus emulator stores its state in SQL Server, so it never runs alone. The module hides that:
private readonly ServiceBusContainer _serviceBus =
new ServiceBusBuilder("mcr.microsoft.com/azure-messaging/servicebus-emulator:2.0.1")
.WithAcceptLicenseAgreement(true)
.WithConfig(Path.Combine(AppContext.BaseDirectory, "servicebus-config.json"))
.Build();
Build() creates a Docker network and a SQL Server container next to the emulator, unless you hand it your own with WithMsSqlContainer. WithAcceptLicenseAgreement(true) accepts the emulator's license; the module won't start it otherwise. The Service Bus emulator image is multi-arch since 2.x. The SQL Server image is amd64 only, so on Apple silicon it runs under Rosetta. That's the slow part: about 5 seconds until SQL Server reports "Recovery is complete", then another 9 until the emulator's health endpoint answers, 14.5 seconds in total.
The emulator doesn't create entities on demand. They come from a JSON config file that it reads once at startup ("changes aren't honored on the fly", per the emulator setup page). WithConfig copies the file into the container, so the test project copies it to its output folder:
<None Update="servicebus-config.json" CopyToOutputDirectory="PreserveNewest" />
Each queue in the file looks like this:
{
"Name": "order-paid",
"Properties": {
"DeadLetteringOnMessageExpiration": false,
"DefaultMessageTimeToLive": "PT1H",
"DuplicateDetectionHistoryTimeWindow": "PT20S",
"ForwardDeadLetteredMessagesTo": "",
"ForwardTo": "",
"LockDuration": "PT5S",
"MaxDeliveryCount": 3,
"RequiresDuplicateDetection": false,
"RequiresSession": false
}
}
The namespace has to be called sbemulatorns; the emulator doesn't accept another name. LockDuration is five seconds instead of the default minute, which is what makes the lock test fast. MaxDeliveryCount decides when a message that keeps failing goes to the dead-letter queue. The file defines four such queues, one per test, so no test receives a message another one left behind: order-paid, order-paid-no-renewal, order-paid-failing (with MaxDeliveryCount: 2) and order-paid-function.
The module gives you two connection strings. GetConnectionString() is the AMQP one with UseDevelopmentEmulator=true, which ServiceBusClient uses for sending and receiving. GetHttpConnectionString() is for ServiceBusAdministrationClient, which the sample doesn't need because the config file creates everything. Readiness is handled too: the module waits for the "Emulator Service is Successfully Up!" log line and a 200 from the emulator's /health endpoint.
One fixture, both emulators, started in parallel
Both containers live in one xUnit v3 assembly fixture, EmulatorsFixture, registered with [assembly: AssemblyFixture(typeof(EmulatorsFixture))] like the Azurite fixture in Part 1. It exposes one Container and one ServiceBusClient for the whole test run:
public Container Orders { get; private set; } = null!;
public ServiceBusClient ServiceBus { get; private set; } = null!;
InitializeAsync starts both containers at once:
await Task.WhenAll(_cosmos.StartAsync(), _serviceBus.StartAsync());
So startup costs the slower of the two, the Service Bus pair, not the sum. Sharing one ServiceBusClient also keeps the suite under a limit: the emulator allows 10 concurrent connections, and every client opens its own. Senders, receivers and processors created from the shared client reuse its connection. Disposal runs in the opposite order, clients first, then both containers in parallel:
public async ValueTask DisposeAsync()
{
_cosmosClient?.Dispose();
if (ServiceBus is not null)
await ServiceBus.DisposeAsync();
await Task.WhenAll(_cosmos.DisposeAsync().AsTask(), _serviceBus.DisposeAsync().AsTask());
}
On my machine, with the images cached, the full test project (Part 1's six tests, the three mocked tests, three against Cosmos DB and four against Service Bus) runs in 34 to 38 seconds. Roughly 15 of those are the two lock tests, which wait out a seven second carrier booking each.
The tests that go red
The Cosmos DB tests above already go red against the first version of the repository: with new PartitionKey(order.Id) back in SaveAsync, the round trip fails with the 400 before it gets to the read. The fix is the one-line change that's in the sample now:
- orders.UpsertItemAsync(order, new PartitionKey(order.Id), cancellationToken: cancellationToken);
+ orders.UpsertItemAsync(order, new PartitionKey(order.CustomerId), cancellationToken: cancellationToken);
The lock needs more setup, because that bug only shows up when time passes. The carrier stub makes the first booking slow and every later one instant:
private sealed class SlowFirstBookingCarrier(TimeSpan firstBookingTakes) : ICarrier
{
private int _bookings;
public int Bookings => _bookings;
public async Task BookAsync(Order order, CancellationToken cancellationToken)
{
if (Interlocked.Increment(ref _bookings) == 1)
await Task.Delay(firstBookingTakes, cancellationToken);
}
}
Seven seconds is longer than the five second LockDuration of the test queues. Both lock tests run the same helper, which sends one order through ShippingRequests and hosts ShipmentHandler in a ServiceBusProcessor:
private async Task<ShipmentRun> ShipOneOrderAsync(string queue, TimeSpan maxAutoLockRenewal)
{
var ct = TestContext.Current.CancellationToken;
var run = new ShipmentRun(new SlowFirstBookingCarrier(SlowBooking));
var handler = new ShipmentHandler(run.Carrier);
await using var sender = emulators.ServiceBus.CreateSender(queue);
await using var processor = emulators.ServiceBus.CreateProcessor(
queue, ShipmentHandler.ProcessorOptions(maxAutoLockRenewal));
processor.ProcessMessageAsync += async args =>
{
run.LastDeliveryCount = args.Message.DeliveryCount;
await handler.HandleAsync(args);
run.Completed = true;
};
processor.ProcessErrorAsync += args =>
{
run.Errors.Enqueue(args.Exception);
return Task.CompletedTask;
};
await new ShippingRequests(sender).RequestAsync(NewPaidOrder(), ct);
await processor.StartProcessingAsync(ct);
await WaitUntilAsync(() => Task.FromResult(run.Completed), TimeSpan.FromSeconds(30));
await processor.StopProcessingAsync(ct);
return run;
}
ShipmentRun collects the bookings, every exception the processor reports, and the delivery count of the last message. The helper stops once a HandleAsync call has completed its message, so a run that ships twice waits for the second delivery. WaitUntilAsync is the polling helper from Part 1's round trip.
The two tests differ in one argument:
[Fact]
public async Task A_booking_slower_than_the_lock_ships_once_while_the_lock_is_renewed()
{
var run = await ShipOneOrderAsync("order-paid", maxAutoLockRenewal: TimeSpan.FromMinutes(5));
Assert.Equal(1, run.Carrier.Bookings);
Assert.Empty(run.Errors);
}
[Fact]
public async Task A_booking_slower_than_the_lock_ships_twice_without_renewal()
{
var run = await ShipOneOrderAsync("order-paid-no-renewal", maxAutoLockRenewal: TimeSpan.Zero);
Assert.Equal(2, run.Carrier.Bookings);
var lockLost = Assert.IsType<ServiceBusException>(Assert.Single(run.Errors));
Assert.Equal(ServiceBusFailureReason.MessageLockLost, lockLost.Reason);
Assert.Equal(2, run.LastDeliveryCount);
}
With five minutes of renewal, the processor renews the lock while the booking runs, and the order ships once. With TimeSpan.Zero, the lock expires after five seconds. The booking finishes at seven, CompleteMessageAsync throws MessageLockLost, the processor passes the exception to ProcessErrorAsync, and the message comes back with DeliveryCount = 2 for a second booking. That's the production bug as a test: it takes 7.8 seconds, the renewed one 7.3.
For a worker on ServiceBusProcessor, the fix is a MaxAutoLockRenewalDuration longer than the slowest booking; for the function app, it's the trigger and its host.json setting below. Neither makes a lost lock impossible. A renewal call can fail, and a process can die between booking and completing. Service Bus delivers at least once, so the booking itself has to tolerate a repeat. ShippingRequests already uses the order id as MessageId, which gives the carrier call an idempotency key to work with.
A carrier that stays down
The other failure is a handler that throws on every delivery, because the carrier API is down:
private sealed class FailingCarrier : ICarrier
{
public Task BookAsync(Order order, CancellationToken cancellationToken) =>
throw new HttpRequestException("Carrier API returned 503");
}
When the handler throws, the processor abandons the message, Service Bus counts the delivery, and after MaxDeliveryCount deliveries the message moves to the dead-letter queue. order-paid-failing allows two:
[Fact]
public async Task A_carrier_that_keeps_failing_dead_letters_the_order_after_max_delivery_count()
{
var ct = TestContext.Current.CancellationToken;
var order = NewPaidOrder();
await using var sender = emulators.ServiceBus.CreateSender("order-paid-failing");
await using var processor = emulators.ServiceBus.CreateProcessor(
"order-paid-failing", ShipmentHandler.ProcessorOptions(TimeSpan.FromMinutes(5)));
processor.ProcessMessageAsync += new ShipmentHandler(new FailingCarrier()).HandleAsync;
processor.ProcessErrorAsync += _ => Task.CompletedTask;
await new ShippingRequests(sender).RequestAsync(order, ct);
await processor.StartProcessingAsync(ct);
await using var deadLetters = emulators.ServiceBus.CreateReceiver(
"order-paid-failing", new ServiceBusReceiverOptions { SubQueue = SubQueue.DeadLetter });
var deadLetter = await deadLetters.ReceiveMessageAsync(TimeSpan.FromSeconds(20), ct);
await processor.StopProcessingAsync(ct);
Assert.NotNull(deadLetter);
Assert.Equal(order.Id, deadLetter.MessageId);
Assert.Equal("MaxDeliveryCountExceeded", deadLetter.DeadLetterReason);
}
The test reads the dead-letter queue through a receiver with SubQueue.DeadLetter and checks that the order arrived with its original message id and DeadLetterReason = "MaxDeliveryCountExceeded". It runs in 0.16 seconds, since an abandoned message is available again immediately and no lock has to run out. What happens to dead-lettered orders after that (an alert, a replay job, a person) is a production decision; the test makes sure they get there.
How production receives: a Service Bus trigger
The function app doesn't run a ServiceBusProcessor of its own. It receives order-paid messages through a Service Bus triggered function, which passes each one to the same ShipmentHandler:
// The trigger renews the lock and completes the message when Run returns; host.json sets the renewal window.
public sealed class ShipmentFunction(ShipmentHandler handler)
{
[Function(nameof(ShipmentFunction))]
public Task Run(
[ServiceBusTrigger(ShippingRequests.QueueName, Connection = "ServiceBusConnection")] ServiceBusReceivedMessage message,
CancellationToken cancellationToken) =>
handler.ShipAsync(message, cancellationToken);
}
The function settles nothing itself. With AutoCompleteMessages at its default of true, the host completes the message after Run returns (trigger attributes), and when Run throws, the extension abandons the message so it's delivered again (extension troubleshooting). That's why the function calls ShipAsync and not HandleAsync: the manual complete belongs to the processor path only. The trigger comes from Microsoft.Azure.Functions.Worker.Extensions.ServiceBus (5.24.0 in Directory.Packages.props), and Program.cs registers the handler and a real carrier:
builder.Services.AddHttpClient<ICarrier, HttpCarrier>(http =>
http.BaseAddress = new Uri(builder.Configuration["CarrierApiUrl"]!));
builder.Services.AddSingleton<ShipmentHandler>();
HttpCarrier is a typed HttpClient that posts the order to the carrier's booking endpoint; the tests replace it with stubs. ServiceBusConnection is the name of the app setting that holds the connection to the namespace.
The lock renewal for the trigger is set in host.json:
{
"version": "2.0",
"extensions": {
"serviceBus": {
"maxAutoLockRenewalDuration": "00:05:00"
}
}
}
Five minutes is the default; the sample writes it out so the value sits next to the code that depends on it. The PeekLock behavior section maps this setting to ServiceBusProcessor.MaxAutoLockRenewalDuration, the value ShipOneOrderAsync passes in. That's why the lock tests don't go through the trigger. Inside the host, a seven second booking never loses its lock, so a trigger-based test would pass with the bug in the code unless the stub booked for more than five minutes, or the test ran a Functions host with its own host.json. The processor runs the same renewal with the window in the test's hands: TimeSpan.Zero is a worker that never renews, five minutes is the trigger's default.
The function class still gets its own test against the emulator, like OrderProcessor got one against Azurite in Part 1. ShippingRequests sends a real message, a receiver takes it off the queue, and the test passes it to Run:
[Fact]
public async Task Run_books_the_order_that_ShippingRequests_sent()
{
var ct = TestContext.Current.CancellationToken;
var order = new Order($"A-{Guid.NewGuid():N}", "c-7", 99.50m, OrderStatus.Paid);
var carrier = Substitute.For<ICarrier>();
await using var sender = emulators.ServiceBus.CreateSender("order-paid-function");
await using var receiver = emulators.ServiceBus.CreateReceiver(
"order-paid-function", new ServiceBusReceiverOptions { ReceiveMode = ServiceBusReceiveMode.ReceiveAndDelete });
await new ShippingRequests(sender).RequestAsync(order, ct);
var message = await receiver.ReceiveMessageAsync(TimeSpan.FromSeconds(10), ct);
await new ShipmentFunction(new ShipmentHandler(carrier)).Run(message, ct);
await carrier.Received(1).BookAsync(order, Arg.Any<CancellationToken>());
}
Unlike the mocked handler test, this one uses whatever the emulator delivered, so it covers the contract between the sender and the trigger. ReceiveAndDelete leaves no lock to settle: that's the host's job in production, and the lock tests cover it going wrong.
Gotchas
SQL Server is the amd64 container. On Apple silicon it needs Rosetta: Colima with vmType: vz and rosetta: true, or the Rosetta setting in Docker Desktop. I didn't measure it under QEMU. Azure SQL Edge, the arm64 workaround in older blog posts, was retired in September 2025. Pin the tags so the cached images stay valid, and keep TESTCONTAINERS_DOCKER_SOCKET_OVERRIDE from Part 1 if you're on Colima.
The Cosmos DB emulator never throttles. Request units are "not yet implemented" in the vNext emulator (feature table), so it never answers 429 Too Many Requests and there's no request charge to assert on. A production container at its provisioned throughput does answer 429, and the SDK retries for you: up to 9 times by default (MaxRetryAttemptsOnRateLimitedRequests), within up to 30 seconds of waiting (MaxRetryWaitTimeOnRateLimitedRequests), and then it throws a CosmosException with status 429. A SaveAsync that takes milliseconds in every test can take half a minute in production and still fail. Set the retry budget on purpose in CosmosClientOptions, sized to what your caller can wait for, and test the throttled path against a real account under load, which is Part 5's job. The same Learn page lists the smaller gaps: no stored procedures, triggers or UDFs, no range, composite or spatial index policies yet, and no bulk execution from the .NET SDK.
A batch trigger doesn't renew per message. maxAutoLockRenewalDuration only applies to functions that receive one message at a time. Switch the trigger to batches for throughput, and the host.json reference points you to the lock settings on the queue instead, where LockDuration is five minutes at most. One slow booking in a batch can push the batch past its lock, and the double shipment is back. Keep slow work on the single-message trigger, or size batches for the slowest call.
The Service Bus emulator isn't your namespace. It has no partitioned entities, speaks AMQP over TCP only (no WebSockets), takes connection strings but no Entra ID, caps messages at 256 KB and time-to-live at one hour, and allows 10 concurrent connections (emulator overview). Entities and messages are gone when the container restarts, and the config file is only read at startup, so a new queue means a new container. The missing Entra ID matters most: in Azure the function connects with a managed identity, and the role assignment it needs is never exercised by this suite.
Readiness log lines aren't a contract. Both modules wait for a log line: Started for Cosmos DB, "Emulator Service is Successfully Up!" (plus the /health endpoint) for Service Bus. Learn calls log-based readiness a legacy signal: its note names the line "System is now fully ready to accept requests", says it might be removed in a future version, and points to the health probe on port 8080 (/ready) instead (health probe). The module waits for Started, not that line, and doesn't publish 8080. If a later tag stops writing the line, StartAsync hangs until its timeout. The way out is a port binding for 8080 and a wait strategy on /ready in the builder.
Running it in CI
The workflow from Part 1 runs the new tests unchanged. The job is the same:
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
Testcontainers starts all three new containers from inside dotnet test, so the job declares no service containers and pulls no images itself. Docker is already on the GitHub-hosted Ubuntu runners, and the first StartAsync pulls what it needs. On the x64 runner, SQL Server runs natively, without Rosetta. The paths filter already includes OrderPipelineDemo.Tests/**, so a change to servicebus-config.json runs it too.
The Cosmos DB emulator page shows another way: the emulator as a GitHub Actions service container next to the job. That gives CI a fixed emulator, but the laptop then needs its own docker run with the same image and settings, and the Service Bus emulator would need SQL Server as a second service container. With Testcontainers, the fixture is the one definition of both emulators, for dotnet test on a Mac and in the pipeline.
The cost is the pull. A hosted runner starts every job with an empty image cache, so this one downloads more than a gigabyte before the first test runs. On ubuntu-latest the whole job takes about two minutes: 94 seconds for the test step, 66 of them for the 16 tests including the cold pulls, and 20 seconds to install the Functions Core Tools. On my machine (Colima on Apple silicon), cold pulls took 76 seconds for the Cosmos DB image (578 MB), 75 for SQL Server (578 MB) and 31 for the Service Bus emulator (86 MB), and with all three cached the test project runs in 34 to 38 seconds. Caching those images and splitting the container tests from the unit tests are Part 6, "Tests in CI".
Conclusion
An in-memory repository and a mocked sender accept any key and any delay, so tests against them check your own logic and nothing beyond it. The partition key path is fixed when the container is created, and the lock clock runs in the broker. Only something that enforces those rules can fail on them, and the emulators do.
They cost more than Azurite in Part 1: three containers instead of one, SQL Server under Rosetta on a Mac, more than a gigabyte of images, and a list of differences from the real services that decides what you still test elsewhere (throttling, identities, batches). For the two rules that broke this pipeline, about 15 seconds of startup per test run is a fair price.
Part 3 moves from runtime behavior to structure: architecture tests with ArchUnitNET, for the layering violations that slip through code review.
Does any test in your suite let a Service Bus lock expire, or does every lock in it come from a mock?

Top comments (0)