Skip to content

Testing Messaging Systems ​

“When testing code that dispatches jobs, you may wish to instruct Laravel to not actually execute the job itself, since the job's code can be tested directly and separately of the code that dispatches it.” — Laravel 13 documentation, Queues: Testing

Summary: Asynchronous code is tested by removing nondeterminism layer by layer: fakes for logic, contracts for messages, real brokers for wiring, fault injection for failure. Focus: The test pyramid for async systems, ports and fakes, Laravel fakes, contract tests, Testcontainers, idempotency, chaos, isolation, flakiness, and CI cost. Learning goal: Choose the cheapest test that can prove each messaging behavior, write it in Go and Laravel 13, and keep the suite deterministic, isolated, and fast.

This chapter owns how to test code that sends and receives messages. Delivery guarantees explains why duplicates and reordering happen; idempotent consumers owns the dedup design being tested here; DLQ owns the failure path; retry and backoff owns the schedules; message design and schema evolution owns compatibility rules; system management owns the Test Message pattern used in production-like checks.

Page map ​

Looking forGo to
Which kind of test proves which behaviorTest pyramid
Interfaces, fakes, stubs and mocks in GoPorts and test doubles
Testing retry and backoff without waitingFake clock
Queue::fake(), Bus::fake(), Event::fake(), Notification::fake()Laravel fakes
Duplicate delivery, out-of-order and poison testsIdempotency, Ordering, Poison
Pact, AsyncAPI and schema registry checksContracts
Real RabbitMQ, Kafka or Redis in a containerIntegration, Broker differences
Unique names, cleanup, parallel testsIsolation
Broker down, crash before ack, rebalanceChaos
Slow, flaky or expensive suitesFlaky tests, CI cost
Commands to tryLab

Everything in one minute ​

LayerWhat it provesSpeedNeeds
Unit test with fakesHandler logic, retry decisions, DLQ routingMillisecondsNothing but the language runtime
Contract testProducer and consumer agree on the message shapeMillisecondsA pact file, schema or golden file
Integration testClient configuration, acks, offsets and topology work on a real brokerSecondsA container runtime such as Docker
End-to-end test messageThe deployed path from producer to consumer worksMinutesA staging environment
Chaos or fault injectionRecovery from a crash, outage or rebalanceSeconds to minutesA way to break a dependency on purpose
Property-based or golden testInvariants hold for many inputs; the wire format has not driftedMillisecondsA generator or a stored file
QuestionWorking answerFailure if ignored
Do I need a broker to test my handler?No: depend on a small interface and pass a fakeA slow suite that nobody runs locally
Can a fake prove the broker config is right?No: only a real broker canGreen tests, broken production wiring
How do I test a 10-minute backoff?Inject a clock and assert the requested sleepsTests that sleep, or retry code that is never tested
Is Queue::fake() testing my job?No: it tests that the job was pushed; call handle() separatelyJobs that are pushed but never exercised
Why does the test pass alone and fail in the suite?Shared queue, group, stream or global stateFlaky failures that hide real ones
Who protects consumers from a renamed field?A contract test, not an integration testAn incident on the first deploy

Where it comes from ​

Martin Fowler's article The Practical Test Pyramid states the rule this chapter applies to messaging: “Write lots of small and fast unit tests.” Add “some more coarse-grained tests and very few high-level tests that test your application from end to end.” His bliki entry on Test Double supplies the vocabulary: “Test Double is a generic term for any case where you replace a production object for testing purposes,” with dummies, fakes, stubs and mocks as kinds. Fake objects “actually have working implementations, but usually take some shortcut which makes them not suitable for production”; an in-memory test database is Fowler's example.

Consumer-driven contracts come from the same pyramid article: “Consumer-Driven Contract tests (CDC tests) let the consumers drive the implementation of a contract.” Pact applies the idea to HTTP and to messages: for messages a Pact interaction is “The minimal expected message - describing the parts of the message that the consumer wants to use” (Pact: how Pact works). The Pact specification page says version 3 “Introduces pact format for message queues” (Pact specification).

Laravel ships its own test doubles for queues, buses, events and notifications. The Laravel 13 events page warns: “After calling Event::fake(), no event listeners will be executed.” Testcontainers is a library family that starts throwaway containers from test code; its Go documentation lists modules for RabbitMQ, Kafka, Redpanda, Redis and Toxiproxy, among others.

Why it exists ​

An async system has more ways to be wrong than a request-response one: messages may be duplicated, reordered, delayed or lost, and the outcome is visible somewhere else later. Tests exist to make these behaviors cheap to provoke and to check.

Tempting approachBetter approach
Start a real broker for every testFakes for logic; a real broker only for wiring
sleep(5) and hope the consumer finishedFake clock, or poll with a deadline for a condition
One shared topic named testA unique topic, queue or stream per test
Assert the message was publishedAssert the message matches a contract
Test only the happy pathInject duplicates, poison input and a downed broker
Run every test on every commitFast layer always; containers on PRs; chaos nightly

Three misunderstandings to remove first: a fake is not a mock (it has working behavior, not scripted expectations); a green fake-based suite says nothing about broker configuration; and an integration test is not a contract test, because it only checks the one producer and consumer it happens to start.

Chaos / E2EIntegrationContractUnit + fakesrun on every saveChaos + end-to-end test messagesfew; minutes; staging or nightly; flaky-proneReal broker in a container (Testcontainers)dozens; seconds each; needs DockerConsumer-driven contracts, schema compatibilityone per message type; millisecondsPorts + fakes + fake clock + table-drivenhundreds; milliseconds each; no networkMove a check down the pyramid whenever a faster layer can prove the same thing.

What it is really about ​

Testing async code means removing the sources of nondeterminism one at a time, so each test can fail for exactly one reason. The application depends on small ports (a publisher, a clock, a dedup store); tests pass in-memory implementations. What the fakes cannot cover is covered by a thin layer of real-broker tests.

Application codeconsumer + retry + DLQPublisher portPublish(ctx, topic, msg)Clock portNow() / Sleep(ctx, d)Inbox portSeen(id) / Mark(id)prod: amqp091,kgo, go-redistest: Memory-Publisher, Busprod: RealClocktest: FakeClockrecords sleepsprod: SQL tabletest: a mapBoxes marked prod run in production, boxes marked test run in tests; the code under test never changes.
Source of nondeterminismHow a test removes it
Wall-clock time (backoff, TTL, delay)Inject a clock; assert requested sleeps or travel time
Broker delivery order and redeliveryAn in-memory bus that you drive step by step, with a Crash()
Concurrency and goroutine schedulingDrive one message at a time; run -race; poll with deadlines
Shared broker stateUnique names per test, cleanup in t.Cleanup
Random IDs and timestampsInject IDs and time; use golden files with fixed values
Network and dependency failuresA failing fake or a fault-injection proxy

An everyday picture ​

Think of a building's fire alarm. You test each smoke detector with its test button (unit test with a fake). You check that the alarm panel and detectors speak the same signal (contract). You trigger a real alarm in a closed building to see that the wiring, the sirens and the doors work (integration). Occasionally you run an unannounced drill with a blocked exit (chaos). You do not burn the building down to test a detector, and a working detector does not prove the sirens are wired.

Concept catalogue ​

The test pyramid for async systems Must-know ​

In plain words: Many fast tests at the bottom, a few slow realistic ones at the top, and each behavior tested at the cheapest layer that can prove it.

Common misunderstanding: “Messaging is integration, so test it with a real broker.” Most messaging bugs are in your handler logic: classification, dedup, retry decisions. Those need no broker.

Definition: The test pyramid (Mike Cohn's idea, discussed in Fowler's article) orders suites by granularity: unit, service or integration, then end-to-end. For messaging, unit tests use fakes; contract tests check the message; integration tests start a broker; end-to-end tests send a real message through staging.

text
1 Handler logic changed        -> unit test with fakes        (ms, every save)
2 Event field renamed          -> contract test               (ms, every commit)
3 Prefetch / ack mode changed  -> integration test, container (s, every PR)
4 New route added in staging   -> end-to-end test message     (min, per deploy)
5 Broker node restarted        -> chaos experiment            (min, nightly)

Real scenarios: A billing consumer's retry budget (unit); an OrderPlaced payload that drops currency (contract); a queue declared durable in code but transient in a policy (integration); a routing key typo in one environment (end-to-end); a consumer that loses messages when RabbitMQ restarts (chaos).

BehaviorCheapest layer that proves it
Retry schedule, DLQ routing, dedupUnit with fakes
Message shape and compatibilityContract, golden file, registry check
Ack mode, prefetch, offsets, MKSTREAMIntegration with a real broker
Environment wiring, credentials, routingEnd-to-end test message
Recovery after crash or partition moveChaos or failure injection

How to use it: For each bug you fix, ask which layer could have caught it and add the test there. If a layer has grown a lot of slow tests that only check logic, push them down.

Ports, fakes, stubs and mocks Must-know ​

In plain words: Hide the broker client behind a tiny interface. In tests, plug in a stand-in that records what happened.

Common misunderstanding: “Mock everything.” Over-mocked tests assert how code calls the client, not what it achieves, and break at every refactor. Prefer a fake with real behavior for things like a publisher or an inbox.

Definition: A port is an interface owned by the application (Publisher, Clock). A dummy fills a parameter. A stub returns canned answers. A fake works with a shortcut: an in-memory publisher that appends to a slice. A mock verifies expected calls. A spy records calls for later assertions. Go uses small consumer-side interfaces; Laravel uses facades with built-in fakes and Mockery for the rest.

text
1 test   -> newConsumer(t): wires MemoryPublisher, FakeClock, fresh Projection
2 test   -> consumer.Process(ctx, msg)
3 SUT    -> Clock.Sleep(1s)   -> FakeClock records [1s], advances virtual time
4 SUT    -> DLQ.Publish(...)  -> MemoryPublisher stores the failure envelope
5 test   -> asserts outcome, sleeps [1s 2s 4s], one DLQ record with reason

Real scenarios: A billing consumer tested with a failing publisher to prove it does not ack when parking fails; an inbox implemented as a map in tests and a SQL table in production; a Laravel service that calls Bus::chain() tested with Bus::fake(); a payment gateway client stubbed to return a canned decline.

DoubleBehaviorUse it forRisk
DummyNoneFilling a required argumentNone
StubCanned answersForcing an error pathDrift from the real client
FakeWorking shortcutPublisher, bus, inbox, clockFake behavior diverges from the broker
MockVerifies callsOne boundary you cannot fakeBrittle, tests implementation
SpyRecords callsAsserting after the actWeaker than a state assertion

How to use it: Define the interface where it is used, keep it to one or two methods, and write the fake next to the interface. Test the fake against the real broker once, in an integration test, so the shortcut stays honest.

Fake clock and time control Must-know ​

In plain words: Do not wait for time. Make time a dependency, and let the test move it.

Common misunderstanding: “Shorten the backoff to 10 ms in tests.” That tests a different configuration, and a real sleep still makes tests slow and flaky under load.

Definition: A fake clock implements the same interface as the real one but records requested sleeps and advances virtual time instantly. In Go 1.25 and later, testing/synctest runs a function in a bubble where, in the documentation's words, “the time package uses a fake clock”; Laravel provides travel(), travelTo() and travelBack() on feature tests.

text
1 Handler attempt 1 fails                 -> Clock.Sleep(1s)   virtual now = +1s
2 Handler attempt 2 fails                 -> Clock.Sleep(2s)   virtual now = +3s
3 Handler attempt 3 succeeds              -> Applied
4 Test asserts Sleeps == [1s 2s], elapsed virtual time == 3s, wall time ~ 0

Real scenarios: Exponential backoff with a cap; message expiry (TTL) checks; scheduled reconciliation jobs; a delayed job released with release(30); a circuit breaker that reopens after a cooldown.

ToolWhereNotes
Injected Clock interfaceGo, any versionWorks with goroutines you control; used in this chapter
testing/synctestGo 1.25 and laterFake time inside a bubble; needs a go directive of 1.25 or newer
$this->travel(), travelTo(), travelBack()Laravel feature testsChanges now() and Carbon
$job->assertReleased(delay: 30)Laravel, withFakeQueueInteractions()Asserts the requested delay without waiting

How to use it: Keep jitter out of the tested path or inject the random source; assert the schedule, not the elapsed wall time. Full retry policy design is in retry and backoff.

Laravel fakes: Queue, Bus, Event, Notification Must-know ​

In plain words: Laravel can swap its queue, bus, event dispatcher and notification channel for recorders. The code under test runs, nothing is really sent, and you ask the recorder what happened.

Common misunderstanding: “Event::fake() only records events.” It also stops listeners from running, so model factories that rely on events (for example a UUID set in a creating listener) must run before you fake.

Definition: Queue::fake(), Bus::fake(), Event::fake() and Notification::fake() replace the underlying service with a recording fake. Faking a subset (Queue::fake([ShipOrder::class])) or all but a subset (->except([...])) lets other jobs or events behave normally.

text
1 test    -> Queue::fake(); Bus::fake()
2 SUT     -> Bus::chain([A, B, C])->onQueue('orders')->dispatch()
3 fake    -> records A with chain [B, C] on queue orders; runs nothing
4 test    -> Queue::assertPushedOn('orders', A::class)
5 test    -> Bus::assertChained([A::class, B::class, C::class])

Real scenarios: An order service dispatches a payment chain; an import dispatches a batch of CSV rows; a controller must not dispatch anything when validation fails; a listener must be registered for an event.

FakeAssertions (Laravel 13)Note
Queue::fake()assertPushed, assertPushedOn, assertPushedOnce, assertPushedTimes, assertNotPushed, assertNothingPushed, assertCount, assertClosurePushedJobs are recorded, not run
Queue::fake()assertPushedWithChain, assertPushedWithoutChainIn the framework's QueueFake class; checks the first job and its chain
Bus::fake()assertDispatched, assertNotDispatched, assertDispatchedSync, assertDispatchedAfterResponse, assertNothingDispatchedAccept a class, closure or property array
Bus::fake()assertChained, assertBatched, assertBatchCount, assertNothingBatchedBus::chainedBatch() nests a batch in a chain
Event::fake()assertDispatched, assertDispatchedOnce, assertNotDispatched, assertNothingDispatched, assertListening->except([...]) and Event::fakeFor(fn) scope the fake
Notification::fake()assertSentTo, assertSentToOnce, assertNothingSent, assertCountPer recipient and class
$job->withFakeBatch()$batch->cancelled(), $batch->addedTest a job's batch interaction without a database
$job->withFakeQueueInteractions()assertReleased, assertDeleted, assertFailed, assertFailedWith, assertNotFailedTest release, delete and fail decisions

How to use it: Call handle() on a job in its own unit test; use the fakes to test only that the right work was queued. The Laravel section below has runnable-looking tests. Internals of the queue drivers are in Laravel queue internals.

Idempotency and duplicate-delivery tests Must-know ​

In plain words: Deliver the same message twice on purpose and check the business effect happened once.

Common misunderstanding: “At-least-once is the broker's problem.” Duplicates reach your handler by design; only your tests can prove your handler survives them.

Definition: An idempotency test replays a message (same ID) after success, after a crash before ack, and after a partial failure, and asserts a single effect. Duplicate delivery is what a broker does when an ack is lost. The design under test is described in idempotent consumers and the inbox.

text
1 Bus.Publish(m1)
2 Consumer.Poll -> Process(m1)        -> Applied, effects = 1
3 Bus.Crash()   -> worker died before Ack; m1 returns, Redelivered = true
4 Consumer.Poll -> Process(m1)        -> Duplicate, effects = 1
5 Delivery.Ack  -> depth 0 ready / 0 in flight

Real scenarios: A payment captured twice; two emails for one order; stock decremented twice after a rebalance; a webhook retried by the sender.

What to replayExpected outcome
Same message, same ID, after successDuplicate, effect count unchanged
Same message after a crash before ackRedelivered once, one effect
Same business event, new transport IDNeeds a business key, not the delivery ID
Two copies processed concurrentlyUnique constraint or lock lets one win

How to use it: In a database-backed inbox, assert with SQL that exactly one row exists:

sql
-- After replaying message m-1 twice, the inbox must hold exactly one row.
CREATE TABLE inbox (
  message_id   text PRIMARY KEY,
  consumer     text NOT NULL,
  processed_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO inbox (message_id, consumer) VALUES ('m-1', 'billing') ON CONFLICT DO NOTHING;
INSERT INTO inbox (message_id, consumer) VALUES ('m-1', 'billing') ON CONFLICT DO NOTHING;
SELECT count(*) FROM inbox WHERE message_id = 'm-1';  -- expect 1

Ordering, out-of-order delivery and property-based tests Important ​

In plain words: Feed the consumer events in a bad order and check the final state is still right.

Common misunderstanding: “Ordering is the broker's guarantee, so I do not need to test it.” Brokers order within a queue or partition; retries, multiple consumers and replays still produce out-of-order arrival at your handler. See ordering and partitioning.

Definition: An out-of-order test delivers sequence 2 before sequence 1. A property-based test generates many random schedules (duplicates, permutations) and asserts an invariant, such as “the projection always converges to the highest sequence.” Go's testing/quick does this in the standard library, though its package documentation says it “is frozen and is not accepting new features”; pgregory.net/rapid adds shrinking and state-machine tests.

text
1 arrive seq 2 ("shipped")  -> Applied
2 arrive seq 1 ("paid")     -> Stale, state stays "shipped"
3 arrive seq 2 again        -> Duplicate
4 property: for any schedule of seq in 1..5, final state == status of max(seq)

Real scenarios: OrderShipped before OrderPaid; a replayed backlog interleaved with live traffic; a retry that lands after a newer event; a Kafka rebalance that moves a partition mid-batch.

TechniqueFindsCost
Hand-written permutation testThe specific reorder you thought ofLow
testing/quick propertyMany schedules, no shrinkingLow
rapid property with shrinkingA minimal failing scheduleAdds a dependency
Model-based test (state machine)Sequences of operations that break invariantsHigher

How to use it: Make the invariant explicit and cheap: last-writer-wins by sequence, or a monotonic version. Keep generated schedules small enough to debug.

Poison messages and DLQ tests Must-know ​

In plain words: Send garbage on purpose and check it ends up parked with evidence, and that the source is not acknowledged if parking fails.

Common misunderstanding: “A DLQ test checks the DLQ exists.” The risky part is the transfer: ack before park loses the message.

Definition: A poison message fails every time under the current consumer. A DLQ test asserts classification, the failure envelope (reason, attempts, original ID), and the settlement order. Design is in dead-letter queue.

text
1 Publish invalid JSON {nope
2 Process -> undecodable            -> park(reason=undecodable)
3 DLQ.Publish fails (broker down)   -> Process returns error, NO ack
4 Retry   -> DLQ.Publish succeeds   -> exactly one parked record

Real scenarios: An unsupported schema version after a bad deploy; a missing required field; a currency code the billing service does not know; an attempt budget exhausted by a flaky dependency.

InputExpected route
Undecodable bytesPark immediately with reason undecodable
Unsupported versionPark with the version in the reason
Permanent business errorPark after one attempt
Transient error, budget exhaustedPark with attempts-exhausted and the attempt count
Transient error that recoversApplied, nothing parked

How to use it: Table-drive the cases (one row per input class) so adding a failure mode is one line.

Contract tests: Pact, AsyncAPI, schema registry Important ​

In plain words: Write down what the consumer needs from a message, and make the producer's build fail if it stops providing it.

Common misunderstanding: “If both services have tests, the contract is tested.” Each side can be green against its own assumptions while disagreeing with the other.

Definition: A consumer-driven contract records the minimal expected message. A message pact (Pact specification version 3 introduced the message format) is verified on the consumer side by feeding the example to the real handler, and on the provider side by running the real producer code and comparing. AsyncAPI describes channels, operations and message payloads in one document. A schema registry enforces schema registry compatibility modes on register: with Confluent Schema Registry, “BACKWARD compatibility means that consumers using the new schema can read data produced with the last schema,” and the default is BACKWARD. Rules and migration paths are in message design and schema evolution.

Consumer testhandler runs on examplemessage from the pactPact file / brokerminimal expected message:fields the consumer usesProvider verificationreal producer code buildsmessage, compare to pactpublishfetchSchema registrycompatibility check onregister: BACKWARDAsyncAPI documentchannels, operations,payload schema lintDeploy gatered build when a pactor schema check failscan-i-deploy asks the pact brokerContracts catch "the producer renamed a field" before any broker is involved.
text
1 Consumer test  -> handler reads example {id, data.order_id, data.currency}
2 Pact written   -> minimal expected message (only fields the consumer uses)
3 Provider build -> real producer code builds the message; verify against the pact
4 Producer drops "currency" -> verification fails; deploy gate stays red

Real scenarios: A producer renames total to total_minor; a new optional field appears (must not break consumers); an enum gets a new value; a team wants a pre-merge check against a registry subject.

ToolChecksWhere it runs
Pact message pactConsumer's minimal expectation vs producer outputConsumer and provider unit tests
AsyncAPI documentChannel, operation and payload descriptionLinting in CI; code generation
Schema registry compatibilityNew schema vs registered versionsRegistry POST /compatibility/subjects/(subject)/versions/(version) or the build plugin
Golden fileExact serialized bytesProducer unit test
Tolerant reader testUnknown fields ignored, required fields enforcedConsumer unit test

How to use it: Use Pact when you control both teams and want consumer-specific expectations; use the registry when many consumers share a topic. Pact has Go and PHP implementations (see the support table on the Pact specification page); check which specification version each supports before copying a snippet.

Golden files for envelopes Important ​

In plain words: Store one known-good serialized message in the repo and compare every build against it.

Common misunderstanding: “Snapshot tests are lazy.” A golden file is a reviewable contract: any change to field names or order shows up as a diff.

Definition: A golden file is a stored expected output. A test serializes a fixed input and compares bytes; an -update flag rewrites the file when you change the format on purpose. The consumer half decodes the same file.

text
1 test serializes fixed envelope -> compares to testdata/order_placed.v1.golden.json
2 field renamed in code          -> byte comparison fails, diff visible in review
3 go test ./msg -update          -> file rewritten deliberately, committed with the change
4 decoder test reads the same file -> consumers still read v1

Real scenarios: An envelope gains a header; a JSON library upgrade changes key order or float formatting; a Protobuf field number changes.

PracticeWhy
Fixed IDs and timestamps in the inputDeterministic bytes
Keep one golden per message type and versionOld versions stay readable
Update only with a conscious flagPrevents silent drift
Decode the golden in a consumer testProves backward readability

How to use it: Pair a golden file with a tolerant-reader test, so adding an optional field passes while removing a required one fails.

Integration tests with Testcontainers Must-know ​

In plain words: Start a real broker in a throwaway container from inside the test, use it, and throw it away.

Common misunderstanding: “Integration tests replace unit tests.” They are slower, harder to debug, and cover few paths. Use them for wiring: connection settings, ack mode, offsets, topology, and the honesty of your fakes.

Definition: Testcontainers starts containers from test code and removes them at the end. testcontainers-go has modules for RabbitMQ, Kafka, Redpanda and Redis, each with a Run(ctx, image, options...) function and helpers such as AmqpURL, Brokers, KafkaSeedBroker and ConnectionString. PHP has a community testcontainers library; many Laravel teams use compose or CI service containers instead.

text
1 TestMain or test -> rabbitmq.Run(ctx, "rabbitmq:3.12.11-management-alpine")
2 test              -> AmqpURL(ctx) -> amqp.Dial; declare a unique exclusive queue
3 test              -> publish, then poll the management API for messages_ready == 1
4 cleanup           -> testcontainers.CleanupContainer(t, ctr) removes the container

Real scenarios: Verifying a prefetch setting; proving manual commit works with a real group; checking a Lua script against real Redis; confirming a DLX policy routes a rejected message.

ConcernReal broker provesFake cannot
Ack, nack, requeue semanticsYesOnly approximates
Consumer group offsets and rebalanceYesNo
Lua scripts and stream commandsYesminiredis covers many, not all
Policies, plugins, TTL and DLXYesNo
Auth, TLS, ACLsYesNo

How to use it: Put container tests behind a build tag or an environment variable, start one container per package, and give each test unique names. All container examples in this chapter are expected, not run: this environment has no Docker.

Test isolation and cleanup Must-know ​

In plain words: Every test gets its own queue, topic or stream, and its own consumer group. Nothing is shared except the container.

Common misunderstanding: “Restart the broker between tests.” That is slow. A unique name per test gives the same isolation in microseconds.

Definition: Test isolation means no test can see another test's messages, offsets or consumer state. Use a unique topic, a consumer group per test, XGROUP CREATE ... MKSTREAM for Redis, and server-named exclusive queues for RabbitMQ. Cleanup runs in t.Cleanup (Go) or tearDown (PHPUnit) so a failing test still cleans up.

Test Aunique(t) = a1f3Test Bunique(t) = 9c2eTest C (parallel)unique(t) = 77d0Shared broker containerstarted once per packagetopic.a1f3 + group.a1f3topic.9c2e + group.9c2etopic.77d0 + group.77d0t.Cleanupdelete topic, group, streamFixed name = shared stateorder-dependent, flakynever reuse:A unique name per test removes cross-test interference without restarting the broker.
text
1 test A: name = unique(t)  -> topic.a1f3, group.a1f3
2 test B: name = unique(t)  -> topic.9c2e, group.9c2e     (parallel with A)
3 both publish and consume  -> neither sees the other's records
4 t.Cleanup                 -> delete topic, group or stream; exclusive queue dies with its connection

Real scenarios: Two tests share orders and each sees the other's messages; a failed test leaves an unacked message that poisons the next run; a fixed consumer group commits an offset that makes a rerun skip records.

BrokerIsolation tool
RabbitMQServer-named exclusive auto-delete queue, or a unique queue name and a unique vhost
KafkaUnique topic created by admin, unique group.id, explicit start offset
Redis StreamsUnique stream key, unique group created with MKSTREAM
LaravelRefreshDatabase, a prefixed queue name, Queue::fake() for unit tests

How to use it: One helper (unique(t, kind)) builds every name from the test name plus random bytes; never type a fixed topic name in a test.

Chaos and failure injection Important ​

In plain words: Break things on purpose in the test and check the system recovers without losing or duplicating work.

Common misunderstanding: “Chaos testing is for production only.” The cheap, valuable part is injecting faults into fakes and containers in CI.

Definition: Failure injection makes a dependency fail in a controlled way: a publisher that returns an error, a bus that crashes before ack, a proxy that drops the connection. Chaos experiments run such faults against a running system. Toxiproxy (a Testcontainers module) can cut or slow a TCP connection between client and broker.

text
1 FailNext(ErrBrokerDown)    -> DLQ.Publish fails once
2 Process(poison)            -> returns error; caller must not Ack
3 Bus.Crash()                -> in-flight messages return, Redelivered = true
4 re-run                     -> message parked once; no double effect

Real scenarios: Broker down during publish; worker killed after processing but before ack; Kafka rebalance moving a partition while a batch is processed; a Redis failover losing the last write; a slow dependency that exhausts the retry budget.

FaultInjected byExpected behavior
Broker unavailable on publishFailNext(err) on the fakeError returned; source not acked
Crash before ackBus.Crash()Redelivery; duplicate absorbed by inbox
Connection cut mid-batchToxiproxy in an integration testClient reconnects; no loss
Rebalance during processingA second consumer joins the same groupDuplicates tolerated; no lost commit
Slow dependencyA stub that sleeps through the fake clockBackoff then DLQ

How to use it: Add one failure-injection test per recovery promise you make in the design doc.

End-to-end tests and test messages Good to know ​

In plain words: Send a clearly marked message through the real deployed path and watch it come out the other side.

Common misunderstanding: “End-to-end tests should cover every case.” They are slow and flaky; keep a few smoke tests per path.

Definition: A test message (the Enterprise Integration Patterns Test Message, whose injector's main role is “to tag messages in order to differentiate 'real' application messages from test messages”) is a synthetic message injected into a live system to verify it end to end; a marker header lets consumers skip side effects or route it to a probe. See system management patterns.

text
1 Probe publishes {type: test, id: probe-123} to the real topic
2 Consumer sees header x-test=true  -> exercises the path, skips billing effect
3 Probe reads the output channel   -> asserts probe-123 arrived within the SLO

Real scenarios: A post-deploy smoke test; a synthetic heartbeat per route; a canary consumer on a new version.

PracticeWhy
Mark test messages with a headerReal consumers can ignore side effects
Use a dedicated tenant or keyKeeps probes out of real aggregates
Alert on missing probeDetects stuck pipelines

How to use it: Keep to one probe per critical route and run it after every deploy.

Flaky tests and time control Must-know ​

In plain words: A flaky test passes and fails on the same code. In async tests the usual cause is waiting for the wrong thing.

Common misunderstanding: “Add a retry or a longer sleep.” That hides the race and slows every run.

Definition: A flaky test has nondeterministic results. Causes: fixed sleep, shared state between tests, wall-clock dependence, ordering assumptions, resource limits in CI.

text
1 Bad:  publish; sleep(2s); assert received          (slow, still races)
2 Good: publish; poll every 50ms up to 5s until received; fail with the last state
3 Best: drive the fake bus one step at a time; no waiting at all

Real scenarios: A consumer test that sleeps 2 seconds and fails on a busy CI runner; two tests using the same queue; a test that depends on map iteration order.

CauseFix
Fixed sleepPoll for a condition with a deadline, or use fakes
Shared namesUnique names per test
Real time in logicInject a clock
Goroutine racesgo test -race; drive one message at a time
Reused container stateOne container per package, unique names, cleanup

How to use it: Run suspect tests with -count=50 and -race; quarantine, then fix, never ignore.

CI cost control Good to know ​

In plain words: Run cheap tests always, containers sometimes, and chaos rarely.

Common misunderstanding: “Run everything on every commit.” Container startup dominates cost and time.

Definition: CI cost control means choosing which layers run when: unit and contract on every push; container integration on pull requests and main; chaos and end-to-end nightly or after deploy.

text
1 push           -> go test -race ./...  and  php artisan test --parallel
2 pull request   -> + go test -tags integration ./...   (needs Docker)
3 main / nightly -> + chaos experiments, soak, schema compatibility against the registry
4 after deploy   -> test-message smoke probe

Real scenarios: A 10-minute suite that blocks every push; a Kafka container started in 80 tests; an image pulled on every run.

LeverEffect
Build tag or env var guardContainer tests skipped without Docker
One container per packagePay startup once
Pin image tags; cache imagesFaster, reproducible
Fail fast: unit before integrationDo not start containers on a red unit run
Parallel tests with unique namesShorter wall time

How to use it: The ci/github-actions.yml snippet shows the shape; treat it as expected, not run.

Mechanics and exact controls ​

Go test knobs Important ​

KnobMeaning
t.Parallel()Run the test in parallel with other parallel tests; requires isolated state
t.Cleanup(fn)Run fn after the test and its subtests, even on failure
t.Setenv(k, v)Set an environment variable for one test; incompatible with t.Parallel()
t.TempDir()A directory removed automatically
go test -raceDetect data races
go test -count=1Disable the result cache; use for integration tests
go test -run NameSelect tests by regexp
-tags integrationInclude files guarded by //go:build integration
TestMain(m)Start one shared container for the package
-update flag (custom)Rewrite golden files deliberately

What each Laravel fake does and does not do Important ​

FakeRuns listeners or jobs?Recording scope
Queue::fake()Jobs are not executedPushes through the queue facade
Bus::fake()Jobs are not executedDispatches, chains and batches
Event::fake()Listeners are not executed (except named events)Events dispatched through the dispatcher
Notification::fake()Nothing is sentNotifications by recipient and class
Queue::fake([A::class])Only A is faked; other jobs are pushed normallySubset
Event::fakeFor(fn)Fake only inside the closureScoped

Common test failures and what they mean Important ​

SymptomCauseFix
Redis BUSYGROUP on group createThe group already exists for this streamUnique group names, or tolerate BUSYGROUP
Redis NOGROUP on readGroup or stream missingXGROUP CREATE ... MKSTREAM first
RabbitMQ RESOURCE_LOCKEDAn exclusive queue used from another connectionDeclare and consume on the same connection
Kafka consumer waits forever on a new groupJava auto.offset.reset defaults to latestSet the start offset explicitly
Test passes alone, fails in suiteShared queue, topic or global stateUnique names; reset fakes per test
Assertion races a management APIBroker statistics lagPoll with a deadline
Event::fake() breaks model factoriesListeners disabledCreate models before faking

Solving classic problems ​

A suite that is slow because it needs a broker ​

SolutionHowAdvantageCost
Ports and fakesInterfaces for publisher, clock, inboxMilliseconds, no DockerFake must be kept honest
miniredis for Redis logicIn-process fake Redis serverNo Docker; supports streams and XGROUP CREATENot every command or edge case
Container per packageTestMain starts oncePay startup onceNeeds Docker in CI
Tags and env guards//go:build integrationLocal runs stay fastEasy to forget in CI

Move the logic tests off the broker first. Then add a small, tagged set of integration tests that run the same worker code against a real container.

A consumer that is only tested on the happy path ​

GapTest to add
DuplicatesProcess the same ID twice; assert one effect
ReorderingDeliver seq 2 then seq 1; assert newest wins
Poison inputUndecodable body; assert parked, source not acked on park failure
Dependency failureFailing stub; assert backoff schedule and DLQ after budget
Crash before ackBus.Crash(); assert redelivery is absorbed

Contract drift between teams ​

SolutionHowAdvantageCost
Golden fileProducer unit test against a stored envelopeZero infrastructureProducer-side only
Pact message pactConsumer writes the pact; provider verifiesConsumer-specific, per-fieldNeeds a pact broker or file sharing
Registry compatibility checkCI calls the compatibility endpointCentral, language-neutralNeeds a registry; check mode choice
AsyncAPI lintValidate the document in CIDocumentation stays trueDescribes, does not verify behavior

Choosing a test layer ​

SituationRecommendationExtra techniqueReason
New retry or DLQ logicUnit test with fakesFake clock, table-drivenFast and deterministic
New field on an eventContract plus golden fileTolerant-reader testProtects consumers
Changing prefetch, ack mode or offsetsContainer integration testUnique namesOnly a real broker proves it
Lua script or stream commandminiredis first, then real RedisMKSTREAM per testCheap first, real second
New route or environmentTest message smoke testMarker headerVerifies deployed wiring
Recovery claim in a design docFailure injection testToxiproxy or fake faultProves the promise
Many events, ordering invariantsProperty-based testtesting/quick or rapidFinds schedules you did not imagine
Laravel job pushes workQueue::fake() or Bus::fake()Separate handle() testSplits dispatch from execution

Go ​

Before ​

A worker that builds its own Redis client, sleeps for real, and acks even when the DLQ write failed. Every test needs a live Redis and 30 seconds per failure. It is intentionally untestable, not broken.

go
// Package before shows a consumer that cannot be unit-tested: it builds its
// own Redis client, sleeps with time.Sleep and writes the DLQ itself. Every
// test needs a live Redis, and the 30-second backoff makes the suite crawl.
// It compiles; it is bad design, not broken code.
package before

import (
	"context"
	"time"

	"github.com/redis/go-redis/v9"
)

type Worker struct{}

func (Worker) Run(ctx context.Context, addr string) error {
	rdb := redis.NewClient(&redis.Options{Addr: addr}) // concrete dependency, hidden inside
	for ctx.Err() == nil {
		res, err := rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
			Group: "billing", Consumer: "w1", Streams: []string{"orders", ">"}, Count: 10, Block: 5 * time.Second,
		}).Result()
		if err != nil && err != redis.Nil {
			return err
		}
		for _, s := range res {
			for _, m := range s.Messages {
				if err := process(m.Values); err != nil {
					time.Sleep(30 * time.Second) // real wall-clock sleep inside the logic
					rdb.XAdd(ctx, &redis.XAddArgs{Stream: "orders.dlq", Values: m.Values})
				}
				rdb.XAck(ctx, "orders", "billing", m.ID) // ack even if the DLQ write failed
			}
		}
	}
	return ctx.Err()
}

func process(map[string]any) error { return nil }

After ​

The application depends on ports: a message type, a publisher, a clock. The fakes are small and live next to the ports.

go
// Package msg holds the ports (small interfaces) that application code
// depends on, plus the message envelope. Production adapters (amqp091-go,
// kgo, go-redis) implement these; tests use the in-memory fakes in fakes.go.
package msg

import (
	"context"
	"encoding/json"
	"time"
)

// Message is the transport-neutral envelope the application sees.
type Message struct {
	ID      string            `json:"id"`
	Key     string            `json:"key"`
	Type    string            `json:"type"`
	Version int               `json:"version"`
	Body    json.RawMessage   `json:"data"`
	Headers map[string]string `json:"headers,omitempty"`
	// Redelivered is set by the broker (or the fake) on a repeat delivery.
	Redelivered bool `json:"-"`
}

// Publisher is the outbound port. Application code never imports a broker client.
type Publisher interface {
	Publish(ctx context.Context, topic string, m Message) error
}

// Clock is the time port. Retry and backoff code sleeps through it, so a test
// can run a ten-minute backoff schedule in microseconds.
type Clock interface {
	Now() time.Time
	Sleep(ctx context.Context, d time.Duration) error
}

// RealClock is the production Clock.
type RealClock struct{}

func (RealClock) Now() time.Time { return time.Now() }

func (RealClock) Sleep(ctx context.Context, d time.Duration) error {
	t := time.NewTimer(d)
	defer t.Stop()
	select {
	case <-t.C:
		return nil
	case <-ctx.Done():
		return ctx.Err()
	}
}
go
package msg

import (
	"context"
	"errors"
	"sync"
	"time"
)

// MemoryPublisher is a fake: a working in-memory implementation with a
// shortcut that makes it unsuitable for production. It records every publish.
type MemoryPublisher struct {
	mu       sync.Mutex
	byTopic  map[string][]Message
	failures []error // consumed one per Publish call, nil entries mean success
}

func NewMemoryPublisher() *MemoryPublisher {
	return &MemoryPublisher{byTopic: map[string][]Message{}}
}

// FailNext queues errors returned by the next len(errs) Publish calls.
// This is failure injection: a broker that is down, a confirm that never came.
func (p *MemoryPublisher) FailNext(errs ...error) {
	p.mu.Lock()
	defer p.mu.Unlock()
	p.failures = append(p.failures, errs...)
}

func (p *MemoryPublisher) Publish(_ context.Context, topic string, m Message) error {
	p.mu.Lock()
	defer p.mu.Unlock()
	if len(p.failures) > 0 {
		err := p.failures[0]
		p.failures = p.failures[1:]
		if err != nil {
			return err
		}
	}
	p.byTopic[topic] = append(p.byTopic[topic], m)
	return nil
}

// Published returns a copy of the messages recorded for a topic.
func (p *MemoryPublisher) Published(topic string) []Message {
	p.mu.Lock()
	defer p.mu.Unlock()
	return append([]Message(nil), p.byTopic[topic]...)
}

// ErrBrokerDown is the canned error used by failure-injection tests.
var ErrBrokerDown = errors.New("broker unavailable")

// FakeClock never really sleeps: Sleep records the requested duration and
// advances virtual time, so tests are fast and deterministic.
type FakeClock struct {
	mu     sync.Mutex
	now    time.Time
	sleeps []time.Duration
}

func NewFakeClock(start time.Time) *FakeClock { return &FakeClock{now: start} }

func (c *FakeClock) Now() time.Time {
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.now
}

func (c *FakeClock) Sleep(ctx context.Context, d time.Duration) error {
	if err := ctx.Err(); err != nil {
		return err
	}
	c.mu.Lock()
	defer c.mu.Unlock()
	c.sleeps = append(c.sleeps, d)
	c.now = c.now.Add(d)
	return nil
}

// Sleeps returns every duration requested so far, in order.
func (c *FakeClock) Sleeps() []time.Duration {
	c.mu.Lock()
	defer c.mu.Unlock()
	return append([]time.Duration(nil), c.sleeps...)
}

The bus fake gives at-least-once semantics for tests: unacked messages come back after Crash() with Redelivered set.

go
package msg

import (
	"context"
	"sync"
)

// Bus is an in-memory, single-queue-per-topic broker with at-least-once
// semantics: a delivery that is not acked is redelivered after Crash().
// It exists to test consumer logic, not to model any real broker.
type Bus struct {
	mu       sync.Mutex
	ready    map[string][]Message
	inflight map[string][]Message
}

func NewBus() *Bus {
	return &Bus{ready: map[string][]Message{}, inflight: map[string][]Message{}}
}

func (b *Bus) Publish(_ context.Context, topic string, m Message) error {
	b.mu.Lock()
	defer b.mu.Unlock()
	b.ready[topic] = append(b.ready[topic], m)
	return nil
}

// Delivery is one unacknowledged hand-off to a consumer.
type Delivery struct {
	Msg   Message
	bus   *Bus
	topic string
}

// Poll hands out the next ready message, or false when the topic is empty.
func (b *Bus) Poll(topic string) (Delivery, bool) {
	b.mu.Lock()
	defer b.mu.Unlock()
	q := b.ready[topic]
	if len(q) == 0 {
		return Delivery{}, false
	}
	m := q[0]
	b.ready[topic] = q[1:]
	b.inflight[topic] = append(b.inflight[topic], m)
	return Delivery{Msg: m, bus: b, topic: topic}, true
}

// Ack settles the delivery; the message will not come back.
func (d Delivery) Ack() {
	d.bus.mu.Lock()
	defer d.bus.mu.Unlock()
	in := d.bus.inflight[d.topic]
	for i, m := range in {
		if m.ID == d.Msg.ID {
			d.bus.inflight[d.topic] = append(in[:i:i], in[i+1:]...)
			return
		}
	}
}

// Crash simulates the consumer dying before it acked: every in-flight message
// returns to the front of the queue, flagged Redelivered.
func (b *Bus) Crash() {
	b.mu.Lock()
	defer b.mu.Unlock()
	for topic, in := range b.inflight {
		back := make([]Message, 0, len(in)+len(b.ready[topic]))
		for _, m := range in {
			m.Redelivered = true
			back = append(back, m)
		}
		b.ready[topic] = append(back, b.ready[topic]...)
		b.inflight[topic] = nil
	}
}

// Depth reports ready and in-flight counts, the numbers a management API shows.
func (b *Bus) Depth(topic string) (ready, inflight int) {
	b.mu.Lock()
	defer b.mu.Unlock()
	return len(b.ready[topic]), len(b.inflight[topic])
}

The consumer under test has a dedup inbox, version-checked state, bounded retry through the clock, and a DLQ that never lets the caller ack if parking failed.

go
// Package orders is the system under test: a consumer with a dedup inbox,
// bounded retry with backoff, version-checked state updates and a DLQ.
// It depends only on the ports in package msg.
package orders

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"sync"
	"time"

	"academy/testing-messaging/msg"
)

// Permanent marks an error that no retry can fix (a poison message).
type Permanent struct{ Err error }

func (p Permanent) Error() string { return "permanent: " + p.Err.Error() }
func (p Permanent) Unwrap() error { return p.Err }

// Outcome says what the consumer did, so tests can assert on it directly.
type Outcome string

const (
	Applied   Outcome = "applied"
	Duplicate Outcome = "duplicate"
	Stale     Outcome = "stale"
	Parked    Outcome = "parked"
)

const DLQTopic = "orders.billing.dlq"

type orderEvent struct {
	OrderID string `json:"order_id"`
	Status  string `json:"status"`
}

// Projection is the read model the consumer maintains: latest status per order.
type Projection struct {
	mu      sync.Mutex
	status  map[string]string
	version map[string]int
	seen    map[string]bool
	effects int
}

func NewProjection() *Projection {
	return &Projection{status: map[string]string{}, version: map[string]int{}, seen: map[string]bool{}}
}

func (p *Projection) Status(order string) string {
	p.mu.Lock()
	defer p.mu.Unlock()
	return p.status[order]
}
func (p *Projection) Effects() int { p.mu.Lock(); defer p.mu.Unlock(); return p.effects }

// Consumer processes one message at a time. Ack is the caller's job and must
// happen only after Process returns a nil error.
type Consumer struct {
	Proj        *Projection
	DLQ         msg.Publisher
	Clock       msg.Clock
	MaxAttempts int
	BaseBackoff time.Duration
	// Handle is the business effect; tests replace it to inject failures.
	Handle func(ctx context.Context, ev orderEvent) error
}

func (c *Consumer) Process(ctx context.Context, m msg.Message) (Outcome, error) {
	var ev orderEvent
	if err := json.Unmarshal(m.Body, &ev); err != nil || ev.OrderID == "" {
		return c.park(ctx, m, "undecodable", 0)
	}
	if m.Version != 1 {
		return c.park(ctx, m, fmt.Sprintf("unsupported-version-%d", m.Version), 0)
	}
	if c.seen(m.ID) {
		return Duplicate, nil
	}
	var last error
	for attempt := 1; attempt <= c.MaxAttempts; attempt++ {
		last = c.Handle(ctx, ev)
		if last == nil {
			return c.commit(m, ev), nil
		}
		var perm Permanent
		if errors.As(last, &perm) {
			return c.park(ctx, m, "permanent", attempt)
		}
		if attempt < c.MaxAttempts {
			backoff := c.BaseBackoff << (attempt - 1)
			if err := c.Clock.Sleep(ctx, backoff); err != nil {
				return "", err
			}
		}
	}
	return c.park(ctx, m, "attempts-exhausted", c.MaxAttempts)
}

func (c *Consumer) seen(id string) bool {
	c.Proj.mu.Lock()
	defer c.Proj.mu.Unlock()
	return c.Proj.seen[id]
}

// commit marks the message as seen and applies it only if it is newer than
// what the projection already holds (last-writer-wins by message sequence).
func (c *Consumer) commit(m msg.Message, ev orderEvent) Outcome {
	p := c.Proj
	p.mu.Lock()
	defer p.mu.Unlock()
	p.seen[m.ID] = true
	seq := sequence(m)
	if seq <= p.version[ev.OrderID] {
		return Stale
	}
	p.version[ev.OrderID] = seq
	p.status[ev.OrderID] = ev.Status
	p.effects++
	return Applied
}

func sequence(m msg.Message) int {
	var n int
	fmt.Sscanf(m.Headers["sequence"], "%d", &n)
	return n
}

// park writes the failure envelope to the DLQ. If that write fails the error
// is returned and the caller must NOT ack: the source stays recoverable.
func (c *Consumer) park(ctx context.Context, m msg.Message, reason string, attempts int) (Outcome, error) {
	dead := m
	dead.Headers = map[string]string{
		"x-reason":      reason,
		"x-attempts":    fmt.Sprint(attempts),
		"x-original-id": m.ID,
		"x-consumer":    "billing",
	}
	if err := c.DLQ.Publish(ctx, DLQTopic, dead); err != nil {
		return "", fmt.Errorf("park %s: %w", m.ID, err)
	}
	return Parked, nil
}

Table-driven tests cover each failure class once; separate tests cover backoff on the fake clock, duplicates, out-of-order delivery, a failed park, and a crash before ack.

go
package orders

import (
	"context"
	"encoding/json"
	"fmt"
	"testing"
	"time"

	"academy/testing-messaging/msg"
)

var t0 = time.Date(2026, 1, 15, 9, 0, 0, 0, time.UTC)

// newConsumer builds a consumer wired to fakes. Every test gets its own
// projection, publisher and clock, so tests share no state and can run in parallel.
func newConsumer(t *testing.T) (*Consumer, *msg.MemoryPublisher, *msg.FakeClock) {
	t.Helper()
	pub := msg.NewMemoryPublisher()
	clk := msg.NewFakeClock(t0)
	c := &Consumer{
		Proj:        NewProjection(),
		DLQ:         pub,
		Clock:       clk,
		MaxAttempts: 4,
		BaseBackoff: time.Second,
		Handle:      func(context.Context, orderEvent) error { return nil },
	}
	return c, pub, clk
}

func order(id string, seq int, status string) msg.Message {
	body, _ := json.Marshal(orderEvent{OrderID: "o-1", Status: status})
	return msg.Message{
		ID: id, Key: "o-1", Type: "order.status_changed", Version: 1,
		Body: body, Headers: map[string]string{"sequence": fmt.Sprint(seq)},
	}
}
go
package orders

import (
	"context"
	"errors"
	"reflect"
	"testing"
	"time"

	"academy/testing-messaging/msg"
)

// Table-driven: one row per failure class, one assertion shape.
func TestProcessClassifiesFailures(t *testing.T) {
	transient := errors.New("db timeout")
	cases := []struct {
		name       string
		msg        msg.Message
		handle     func(context.Context, orderEvent) error
		wantOut    Outcome
		wantReason string
		wantSleeps []time.Duration
	}{
		{"success", order("m1", 1, "paid"), nil, Applied, "", nil},
		{"undecodable body", msg.Message{ID: "m2", Version: 1, Body: []byte("{nope")}, nil, Parked, "undecodable", nil},
		{"unsupported version", func() msg.Message { m := order("m3", 1, "paid"); m.Version = 9; return m }(), nil, Parked, "unsupported-version-9", nil},
		{"permanent business error", order("m4", 1, "paid"),
			func(context.Context, orderEvent) error { return Permanent{errors.New("unknown currency")} },
			Parked, "permanent", nil},
		{"transient forever exhausts budget", order("m5", 1, "paid"),
			func(context.Context, orderEvent) error { return transient },
			Parked, "attempts-exhausted", []time.Duration{time.Second, 2 * time.Second, 4 * time.Second}},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			t.Parallel()
			c, dlq, clk := newConsumer(t)
			if tc.handle != nil {
				c.Handle = tc.handle
			}
			out, err := c.Process(context.Background(), tc.msg)
			if err != nil {
				t.Fatalf("Process: %v", err)
			}
			if out != tc.wantOut {
				t.Fatalf("outcome = %s, want %s", out, tc.wantOut)
			}
			parked := dlq.Published(DLQTopic)
			if tc.wantReason == "" && len(parked) != 0 {
				t.Fatalf("unexpected DLQ traffic: %v", parked)
			}
			if tc.wantReason != "" {
				if len(parked) != 1 || parked[0].Headers["x-reason"] != tc.wantReason {
					t.Fatalf("DLQ = %+v, want one record with reason %q", parked, tc.wantReason)
				}
				if parked[0].Headers["x-original-id"] != tc.msg.ID {
					t.Fatalf("parked record lost its source identity")
				}
			}
			if got := clk.Sleeps(); !reflect.DeepEqual(got, tc.wantSleeps) && !(len(got) == 0 && len(tc.wantSleeps) == 0) {
				t.Fatalf("backoff schedule = %v, want %v", got, tc.wantSleeps)
			}
		})
	}
}

// A fake clock turns "waits 1s, 2s, then succeeds" into an instant assertion.
func TestTransientFailureRecoversAfterBackoff(t *testing.T) {
	c, dlq, clk := newConsumer(t)
	calls := 0
	c.Handle = func(context.Context, orderEvent) error {
		calls++
		if calls < 3 {
			return errors.New("503 from payment gateway")
		}
		return nil
	}
	out, err := c.Process(context.Background(), order("m1", 1, "paid"))
	if err != nil || out != Applied {
		t.Fatalf("out=%s err=%v", out, err)
	}
	if want := []time.Duration{time.Second, 2 * time.Second}; !reflect.DeepEqual(clk.Sleeps(), want) {
		t.Fatalf("sleeps = %v, want %v", clk.Sleeps(), want)
	}
	if got := clk.Now().Sub(t0); got != 3*time.Second {
		t.Fatalf("virtual elapsed = %v, want 3s", got)
	}
	if len(dlq.Published(DLQTopic)) != 0 {
		t.Fatal("a recovered message must not be parked")
	}
}

// Duplicate delivery: the same message ID twice yields one business effect.
func TestDuplicateDeliveryHasOneEffect(t *testing.T) {
	c, _, _ := newConsumer(t)
	m := order("m1", 1, "paid")
	first, _ := c.Process(context.Background(), m)
	second, _ := c.Process(context.Background(), m)
	if first != Applied || second != Duplicate {
		t.Fatalf("outcomes = %s, %s", first, second)
	}
	if c.Proj.Effects() != 1 {
		t.Fatalf("effects = %d, want 1", c.Proj.Effects())
	}
}

// Out-of-order delivery: sequence 2 arrives before sequence 1.
func TestOutOfOrderDeliveryKeepsNewestState(t *testing.T) {
	c, _, _ := newConsumer(t)
	ctx := context.Background()
	c.Process(ctx, order("m2", 2, "shipped"))
	out, _ := c.Process(ctx, order("m1", 1, "paid"))
	if out != Stale {
		t.Fatalf("late older event outcome = %s, want stale", out)
	}
	if got := c.Proj.Status("o-1"); got != "shipped" {
		t.Fatalf("status = %q, want shipped", got)
	}
}

// Chaos: the DLQ publish fails. Process must return an error so the caller
// does not ack; the message stays recoverable and the retry succeeds.
func TestParkFailureIsReturnedAndNotAcked(t *testing.T) {
	c, dlq, _ := newConsumer(t)
	bad := msg.Message{ID: "poison", Version: 1, Body: []byte("{nope")}
	dlq.FailNext(msg.ErrBrokerDown)
	if _, err := c.Process(context.Background(), bad); !errors.Is(err, msg.ErrBrokerDown) {
		t.Fatalf("err = %v, want broker down", err)
	}
	if out, err := c.Process(context.Background(), bad); err != nil || out != Parked {
		t.Fatalf("second attempt out=%s err=%v", out, err)
	}
	if n := len(dlq.Published(DLQTopic)); n != 1 {
		t.Fatalf("DLQ records = %d, want exactly 1", n)
	}
}

// Chaos: crash after processing but before the ack. The broker redelivers;
// the inbox absorbs the duplicate.
func TestCrashBeforeAckRedeliversWithoutDoubleEffect(t *testing.T) {
	c, _, _ := newConsumer(t)
	bus := msg.NewBus()
	ctx := context.Background()
	bus.Publish(ctx, "orders", order("m1", 1, "paid"))

	d, _ := bus.Poll("orders")
	if out, _ := c.Process(ctx, d.Msg); out != Applied {
		t.Fatalf("first outcome = %s", out)
	}
	bus.Crash() // the worker dies before d.Ack()

	d, ok := bus.Poll("orders")
	if !ok || !d.Msg.Redelivered {
		t.Fatalf("expected a redelivered message, got ok=%v redelivered=%v", ok, d.Msg.Redelivered)
	}
	if out, _ := c.Process(ctx, d.Msg); out != Duplicate {
		t.Fatalf("redelivery outcome = %s, want duplicate", out)
	}
	d.Ack()
	if ready, inflight := bus.Depth("orders"); ready != 0 || inflight != 0 {
		t.Fatalf("depth = %d/%d, want 0/0", ready, inflight)
	}
	if c.Proj.Effects() != 1 {
		t.Fatalf("effects = %d, want 1", c.Proj.Effects())
	}
}

A property test replays arbitrary schedules and checks convergence.

go
package orders

import (
	"context"
	"fmt"
	"testing"
	"testing/quick"
)

// Property: for ANY arrival schedule made of sequences 1..5, with any
// duplicates and any order, the projection ends at the highest sequence seen
// and every distinct message ID is applied or ignored at most once.
func TestProjectionConvergesUnderAnySchedule(t *testing.T) {
	statuses := []string{"", "created", "paid", "packed", "shipped", "delivered"}
	prop := func(schedule []uint8) bool {
		c, _, _ := newConsumer(t)
		highest := 0
		for _, raw := range schedule {
			seq := int(raw%5) + 1
			if seq > highest {
				highest = seq
			}
			// The message ID is derived from the sequence, so a repeated
			// sequence is a duplicate delivery of the same message.
			m := order(fmt.Sprintf("m%d", seq), seq, statuses[seq])
			if _, err := c.Process(context.Background(), m); err != nil {
				return false
			}
		}
		if highest == 0 {
			return c.Proj.Status("o-1") == ""
		}
		return c.Proj.Status("o-1") == statuses[highest] && c.Proj.Effects() <= 5
	}
	if err := quick.Check(prop, &quick.Config{MaxCount: 500}); err != nil {
		t.Fatal(err)
	}
}

A golden-file test pins the envelope bytes; the decoder test reads the same file.

go
package msg

import (
	"bytes"
	"encoding/json"
	"flag"
	"os"
	"path/filepath"
	"testing"
)

var update = flag.Bool("update", false, "rewrite golden files")

// Golden-file test: the serialized envelope is a public contract. Any change
// to field names, order or defaults shows up as a reviewable diff of
// testdata/*.golden.json instead of a silent break in a consumer.
func TestEnvelopeGolden(t *testing.T) {
	m := Message{
		ID:      "0194f2c0-7d2e-7b3a-9a41-2f6f0c1d8e55",
		Key:     "order-1042",
		Type:    "order.placed",
		Version: 1,
		Body:    json.RawMessage(`{"order_id":"order-1042","total_minor":4599,"currency":"USD"}`),
		Headers: map[string]string{"correlation-id": "req-7f3a", "sequence": "1"},
	}
	got, err := json.MarshalIndent(m, "", "  ")
	if err != nil {
		t.Fatal(err)
	}
	got = append(got, '\n')

	path := filepath.Join("testdata", "order_placed.v1.golden.json")
	if *update {
		if err := os.WriteFile(path, got, 0o644); err != nil {
			t.Fatal(err)
		}
	}
	want, err := os.ReadFile(path)
	if err != nil {
		t.Fatalf("missing golden file (run: go test ./msg -update): %v", err)
	}
	if !bytes.Equal(got, want) {
		t.Fatalf("envelope changed.\n--- got ---\n%s--- want ---\n%s", got, want)
	}
}

// A decoder written for v1 must keep reading the golden bytes: the consumer
// half of the same contract.
func TestGoldenStillDecodes(t *testing.T) {
	raw, err := os.ReadFile(filepath.Join("testdata", "order_placed.v1.golden.json"))
	if err != nil {
		t.Fatal(err)
	}
	var m Message
	if err := json.Unmarshal(raw, &m); err != nil {
		t.Fatal(err)
	}
	if m.Type != "order.placed" || m.Version != 1 || m.Key != "order-1042" {
		t.Fatalf("decoded %+v", m)
	}
}
json
{
  "id": "0194f2c0-7d2e-7b3a-9a41-2f6f0c1d8e55",
  "key": "order-1042",
  "type": "order.placed",
  "version": 1,
  "data": {
    "order_id": "order-1042",
    "total_minor": 4599,
    "currency": "USD"
  },
  "headers": {
    "correlation-id": "req-7f3a",
    "sequence": "1"
  }
}

The Go angle ​

Go's idiom is a small interface defined by the consumer, plus tests in the same package. Run go test -race -count=1 ./...; none of these tests need a network. Use t.Parallel() only where tests share no state: here each test builds its own consumer, publisher and clock. The Go 1.25 testing/synctest package can replace the injected clock for code that uses time directly; this module keeps go 1.24 and an explicit Clock so the tests run on both.

Laravel ​

Before ​

Laravel code that mixes dispatch, events and notifications is easiest to test when each call goes through a facade that has a fake. The service below dispatches an event, a four-job chain, and a notification; there is no broker involved when the fakes are active.

php
<?php

namespace App\Services;

use App\Events\OrderPlaced;
use App\Jobs\ProcessPayment;
use App\Jobs\RecordShipment;
use App\Jobs\ShipOrder;
use App\Jobs\UpdateInventory;
use App\Models\Order;
use App\Notifications\OrderReceived;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Notification;

// System under test for the fakes: one event, one chain, one notification.
class PlaceOrder
{
    public function __invoke(Order $order): void
    {
        event(new OrderPlaced($order));

        Bus::chain([
            new ProcessPayment($order->id),
            new ShipOrder($order->id),
            new RecordShipment($order->id),
            new UpdateInventory($order->id),
        ])->onQueue('orders')->dispatch();

        Notification::send($order->customer, new OrderReceived($order));
    }
}

After ​

Feature tests fake the queue, bus, events or notifications, run the service, and assert what was recorded. Create models before Event::fake().

php
<?php

namespace Tests\Feature;

use App\Events\OrderPlaced;
use App\Jobs\ProcessPayment;
use App\Jobs\RecordShipment;
use App\Jobs\ShipOrder;
use App\Jobs\UpdateInventory;
use App\Listeners\SendOrderReceipt;
use App\Models\Order;
use App\Notifications\OrderReceived;
use App\Services\PlaceOrder;
use Illuminate\Events\CallQueuedListener;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Queue;
use Tests\TestCase;

class PlaceOrderTest extends TestCase
{
    use RefreshDatabase;

    public function test_queue_fake_records_the_first_job_and_its_chain(): void
    {
        // Create models BEFORE faking events: Event::fake() stops model listeners.
        $order = Order::factory()->create();
        Queue::fake();

        app(PlaceOrder::class)($order);

        Queue::assertPushedOn('orders', ProcessPayment::class);
        Queue::assertPushedOnce(ProcessPayment::class);
        Queue::assertPushedWithChain(ProcessPayment::class, [
            ShipOrder::class,
            RecordShipment::class,
            UpdateInventory::class,
        ]);
        // Chained successors are not pushed until the first job succeeds.
        Queue::assertNotPushed(ShipOrder::class);
        Queue::assertCount(1);
    }

    public function test_bus_fake_asserts_the_whole_chain_shape(): void
    {
        $order = Order::factory()->create();
        Bus::fake();

        app(PlaceOrder::class)($order);

        Bus::assertChained([
            ProcessPayment::class,
            ShipOrder::class,
            RecordShipment::class,
            UpdateInventory::class,
        ]);
        Bus::assertDispatched(ProcessPayment::class, ['orderId' => $order->id]);
        Bus::assertNothingBatched();
    }

    public function test_event_fake_records_dispatch_and_skips_listeners(): void
    {
        $order = Order::factory()->create();
        Event::fake([OrderPlaced::class]); // other events (model events) still run
        Bus::fake();

        app(PlaceOrder::class)($order);

        Event::assertDispatched(OrderPlaced::class, fn (OrderPlaced $e) => $e->order->is($order));
        Event::assertDispatchedOnce(OrderPlaced::class);
    }

    public function test_event_fake_except_lets_one_event_reach_its_listeners(): void
    {
        $order = Order::factory()->create();
        Event::fake()->except([OrderPlaced::class]); // fake every event except OrderPlaced
        Queue::fake();

        app(PlaceOrder::class)($order);

        // OrderPlaced ran for real, so its queued listener became a queued job.
        Queue::assertPushed(
            CallQueuedListener::class,
            fn (CallQueuedListener $job) => $job->class === SendOrderReceipt::class,
        );
    }

    public function test_notification_fake_checks_recipient_and_class(): void
    {
        $order = Order::factory()->create();
        Notification::fake();
        Bus::fake();

        app(PlaceOrder::class)($order);

        Notification::assertSentTo($order->customer, OrderReceived::class);
        Notification::assertCount(1);
    }

    public function test_nothing_is_pushed_when_the_order_is_invalid(): void
    {
        Queue::fake();
        Bus::fake();

        $this->postJson('/orders', [])->assertUnprocessable();

        Queue::assertNothingPushed();
        Bus::assertNothingDispatched();
    }
}

Batches use Bus::assertBatched, assertBatchCount and withFakeBatch.

php
<?php

namespace App\Jobs;

use Illuminate\Bus\Batchable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;

class ProcessCsvRow implements ShouldQueue
{
    use Batchable, Queueable;

    public function __construct(public int $row, public bool $corrupt = false) {}

    public function handle(): void
    {
        if ($this->batch()?->cancelled()) {
            return; // a sibling already cancelled the batch
        }

        if ($this->corrupt) {
            $this->batch()?->cancel();
        }
    }
}
php
<?php

namespace Tests\Feature;

use App\Jobs\ProcessCsvRow;
use Illuminate\Bus\PendingBatch;
use Illuminate\Support\Facades\Bus;
use Illuminate\Http\UploadedFile;
use Tests\TestCase;

class BatchTest extends TestCase
{
    public function test_import_dispatches_one_named_batch_of_three_rows(): void
    {
        Bus::fake();

        $this->post('/imports', ['file' => UploadedFile::fake()->createWithContent('rows.csv', "a\nb\nc\n")])
            ->assertAccepted();

        Bus::assertBatched(function (PendingBatch $batch) {
            return $batch->name === 'Import CSV' && $batch->jobs->count() === 3;
        });
        Bus::assertBatched(fn (PendingBatch $batch) => $batch->hasJobs([
            fn (ProcessCsvRow $job) => $job->row === 1,
            fn (ProcessCsvRow $job) => $job->row === 2,
            fn (ProcessCsvRow $job) => $job->row === 3,
        ]));
        Bus::assertBatchCount(1);
    }

    public function test_job_cancels_its_batch_on_a_corrupt_row(): void
    {
        // withFakeBatch gives the job a fake batch it can cancel, no database needed.
        [$job, $batch] = (new ProcessCsvRow(row: 99, corrupt: true))->withFakeBatch();

        $job->handle();

        $this->assertTrue($batch->cancelled());
    }
}

A job and its middleware are tested directly; withFakeQueueInteractions() asserts release, delete and fail decisions; failed() is called by hand.

php
<?php

namespace App\Jobs;

use App\Exceptions\CardDeclined;
use App\Jobs\Middleware\SkipIfAlreadyProcessed;
use App\Services\PaymentGateway;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Support\Facades\Log;
use Throwable;

#[Tries(3)]
class ProcessPayment implements ShouldQueue
{
    use Queueable;

    public function __construct(public int $orderId) {}

    /** @return array<int, object> */
    public function middleware(): array
    {
        return [new SkipIfAlreadyProcessed("payment:{$this->orderId}")];
    }

    public function handle(PaymentGateway $gateway): void
    {
        try {
            $gateway->charge($this->orderId, idempotencyKey: "order-{$this->orderId}");
        } catch (CardDeclined $e) {
            $this->fail($e); // retrying cannot help
        }
    }

    public function failed(?Throwable $exception): void
    {
        Log::warning('payment parked', ['order_id' => $this->orderId, 'exception' => $exception ? $exception::class : null]);
    }
}
php
<?php

namespace App\Jobs\Middleware;

use Closure;
use Illuminate\Support\Facades\Cache;

// Job middleware: wraps handle(). Pure PHP, so a test can call it with a closure.
class SkipIfAlreadyProcessed
{
    public function __construct(private string $key) {}

    public function handle(object $job, Closure $next): void
    {
        if (Cache::has("done:{$this->key}")) {
            $job->delete(); // duplicate delivery: acknowledge and do nothing
            return;
        }

        $next($job);

        Cache::put("done:{$this->key}", true, now()->addDay());
    }
}
php
<?php

namespace Tests\Unit;

use App\Exceptions\CardDeclined;
use App\Jobs\Middleware\SkipIfAlreadyProcessed;
use App\Jobs\ProcessPayment;
use App\Services\PaymentGateway;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Mockery;
use Tests\TestCase;

class ProcessPaymentTest extends TestCase
{
    public function test_handle_charges_with_a_stable_idempotency_key(): void
    {
        $gateway = Mockery::mock(PaymentGateway::class);
        $gateway->shouldReceive('charge')->once()->with(42, idempotencyKey: 'order-42');

        (new ProcessPayment(42))->handle($gateway);
    }

    public function test_declined_card_fails_the_job_without_retrying(): void
    {
        $gateway = Mockery::mock(PaymentGateway::class);
        $gateway->shouldReceive('charge')->andThrow(new CardDeclined());

        $job = (new ProcessPayment(42))->withFakeQueueInteractions();
        $job->handle($gateway);

        $job->assertFailedWith(CardDeclined::class);
        $job->assertNotReleased();
    }

    public function test_failed_hook_logs_the_class_not_the_payload(): void
    {
        Log::spy();

        (new ProcessPayment(42))->failed(new CardDeclined());

        Log::shouldHaveReceived('warning')->once();
    }

    public function test_middleware_skips_a_duplicate_delivery(): void
    {
        Cache::put('done:payment:42', true);
        $job = (new ProcessPayment(42))->withFakeQueueInteractions();
        $ran = false;

        (new SkipIfAlreadyProcessed('payment:42'))->handle($job, function () use (&$ran) {
            $ran = true;
        });

        $this->assertFalse($ran);
        $job->assertDeleted();
    }

    public function test_middleware_marks_success_so_the_next_delivery_is_skipped(): void
    {
        Cache::forget('done:payment:7');
        $job = (new ProcessPayment(7))->withFakeQueueInteractions();

        (new SkipIfAlreadyProcessed('payment:7'))->handle($job, fn () => null);

        $this->assertTrue(Cache::has('done:payment:7'));
    }
}

A contract test for an integration envelope: the producer output matches a golden file, and a tolerant reader accepts new fields but rejects missing required ones.

php
<?php

namespace App\Messaging;

use DateTimeImmutable;
use DateTimeInterface;
use JsonException;

// The integration envelope other services consume. Its JSON shape is a public contract.
final class OrderPlacedEnvelope
{
    public const TYPE = 'order.placed';
    public const VERSION = 1;

    public function __construct(
        public readonly string $id,
        public readonly string $orderId,
        public readonly int $totalMinor,
        public readonly string $currency,
        public readonly DateTimeImmutable $occurredAt,
    ) {}

    /** @return array<string, mixed> */
    public function toArray(): array
    {
        return [
            'id' => $this->id,
            'type' => self::TYPE,
            'version' => self::VERSION,
            'occurred_at' => $this->occurredAt->format(DateTimeInterface::ATOM),
            'data' => [
                'order_id' => $this->orderId,
                'total_minor' => $this->totalMinor,
                'currency' => $this->currency,
            ],
        ];
    }

    public function toJson(): string
    {
        return json_encode($this->toArray(), JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    }

    /** Tolerant reader: ignores unknown fields, rejects missing required ones. */
    public static function fromJson(string $json): self
    {
        try {
            $d = json_decode($json, true, flags: JSON_THROW_ON_ERROR);
            return new self(
                $d['id'],
                $d['data']['order_id'],
                (int) $d['data']['total_minor'],
                $d['data']['currency'],
                new DateTimeImmutable($d['occurred_at']),
            );
        } catch (JsonException|\Throwable $e) {
            throw new \InvalidArgumentException('undecodable order.placed envelope', 0, $e);
        }
    }
}
php
<?php

namespace Tests\Unit;

use App\Messaging\OrderPlacedEnvelope;
use DateTimeImmutable;
use InvalidArgumentException;
use PHPUnit\Framework\TestCase;

// Plain PHPUnit: a contract test needs no framework boot and no broker.
class OrderPlacedContractTest extends TestCase
{
    private function envelope(): OrderPlacedEnvelope
    {
        return new OrderPlacedEnvelope(
            '0194f2c0-7d2e-7b3a-9a41-2f6f0c1d8e55',
            'order-1042',
            4599,
            'USD',
            new DateTimeImmutable('2026-01-15T09:00:00+00:00'),
        );
    }

    public function test_producer_output_matches_the_golden_file(): void
    {
        $golden = file_get_contents(__DIR__.'/golden/order_placed.v1.json');

        $this->assertSame(trim($golden), $this->envelope()->toJson());
    }

    public function test_consumer_reads_the_golden_file_and_ignores_unknown_fields(): void
    {
        $withExtra = json_decode(file_get_contents(__DIR__.'/golden/order_placed.v1.json'), true);
        $withExtra['data']['coupon'] = 'SPRING'; // a newer producer added a field

        $read = OrderPlacedEnvelope::fromJson(json_encode($withExtra));

        $this->assertSame('order-1042', $read->orderId);
        $this->assertSame(4599, $read->totalMinor);
    }

    public function test_consumer_rejects_a_message_missing_a_required_field(): void
    {
        $this->expectException(InvalidArgumentException::class);

        OrderPlacedEnvelope::fromJson('{"id":"x","type":"order.placed","version":1}');
    }

    public function test_required_fields_are_exactly_the_published_contract(): void
    {
        $keys = array_keys($this->envelope()->toArray());
        sort($keys);

        // Removing or renaming any of these breaks every consumer.
        $this->assertSame(['data', 'id', 'occurred_at', 'type', 'version'], $keys);
    }
}
json
{
    "id": "0194f2c0-7d2e-7b3a-9a41-2f6f0c1d8e55",
    "type": "order.placed",
    "version": 1,
    "occurred_at": "2026-01-15T09:00:00+00:00",
    "data": {
        "order_id": "order-1042",
        "total_minor": 4599,
        "currency": "USD"
    }
}

The same assertions in Pest style:

php
<?php

use App\Jobs\ShipOrder;
use App\Models\Order;
use App\Services\PlaceOrder;
use Illuminate\Support\Facades\Queue;

// The same assertions in Pest style: a closure per test, the fake set up first.
test('only ShipOrder is faked; other jobs are pushed normally', function () {
    $order = Order::factory()->create();
    Queue::fake([ShipOrder::class]);

    app(PlaceOrder::class)($order);

    Queue::assertPushedTimes(ShipOrder::class, 1);
});

test('fake everything except ShipOrder', function () {
    $order = Order::factory()->create();
    Queue::fake()->except([ShipOrder::class]);

    app(PlaceOrder::class)($order);

    Queue::assertNotPushed(ShipOrder::class);
});

The Laravel angle ​

Laravel 13 documents “database, Amazon SQS, Redis, and Beanstalkd drivers”; RabbitMQ and Kafka need packages, so tests that use those packages need a container or the fakes. Use Queue::fake() when you only care that a job was pushed, and call handle() yourself when you care what it does. The Queue::fake() family also accepts a closure or an array of expected property values; array values compare with strict equality and Eloquent models with is. Bus::fake() is the one that can see chains and batches (assertChained, assertBatched). Queue::assertPushedWithChain and assertPushedWithoutChain exist on the framework's QueueFake class; confirm them against your installed framework version before relying on them, because the Laravel documentation page does not list them.

For time, travel(), travelTo() and travelBack() change now(). For integration tests, either run a service container in CI or use a community PHP Testcontainers library; verify its maturity and API before adopting it. Set QUEUE_CONNECTION explicitly in phpunit.xml so a test never reaches a real queue by accident. A Mockery mock is the right tool for a boundary you cannot fake, such as the payment gateway.

NeedUse
Was the job pushed, where, how many timesQueue::assertPushed, assertPushedOn, assertPushedTimes
Was a chain or batch dispatchedBus::assertChained, assertBatched, assertBatchCount
Did the code dispatch an eventEvent::assertDispatched
Did a listener get queuedQueue::assertPushed(CallQueuedListener::class, fn ...)
Was a notification sentNotification::assertSentTo
What does the job doInstantiate it and call handle()
Did the job release or failwithFakeQueueInteractions() assertions
Does the failure hook log safelyCall failed() with a Log::spy()

Broker differences ​

RabbitMQ ​

RabbitMQ gives you queue properties that make isolation easy: a server-named, exclusive, auto-delete queue disappears with its connection, so a failed test leaves nothing behind. The RabbitMQ documentation says an attempt to use an exclusive queue from a different connection “will result in a channel-level exception RESOURCE_LOCKED”, so declare and consume on one connection. The management HTTP API exposes GET /api/queues/{vhost}/{name} with messages_ready; use it to assert broker-side state, and poll because the numbers can lag. The Testcontainers RabbitMQ module provides Run, AmqpURL() and HttpURL(). The example is expected, not run (needs Docker).

go
//go:build integration

package integration

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"testing"
	"time"

	amqp "github.com/rabbitmq/amqp091-go"
	"github.com/testcontainers/testcontainers-go"
	"github.com/testcontainers/testcontainers-go/modules/rabbitmq"
)

// expected, not run: needs a Docker daemon.
func TestRabbitMQExclusiveQueueAndManagementAPI(t *testing.T) {
	ctx := context.Background()
	ctr, err := rabbitmq.Run(ctx, "rabbitmq:3.12.11-management-alpine",
		rabbitmq.WithAdminUsername("admin"), rabbitmq.WithAdminPassword("password"))
	testcontainers.CleanupContainer(t, ctr) // terminates the container when the test ends
	if err != nil {
		t.Fatal(err)
	}

	url, err := ctr.AmqpURL(ctx)
	if err != nil {
		t.Fatal(err)
	}
	conn, err := amqp.Dial(url)
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { _ = conn.Close() })
	ch, err := conn.Channel()
	if err != nil {
		t.Fatal(err)
	}

	// Exclusive + auto-delete: the broker removes the queue when this
	// connection closes, so a failed test cannot leave a queue behind.
	q, err := ch.QueueDeclare(unique(t, "q"), false, true, true, false, nil)
	if err != nil {
		t.Fatal(err)
	}
	if err := ch.PublishWithContext(ctx, "", q.Name, false, false,
		amqp.Publishing{MessageId: "m-1", Body: []byte(`{"order_id":"o-1"}`)}); err != nil {
		t.Fatal(err)
	}

	// Assert broker-side state through the management HTTP API. Its numbers
	// can lag behind the broker, so poll instead of asserting once.
	base, err := ctr.HttpURL(ctx)
	if err != nil {
		t.Fatal(err)
	}
	deadline := time.Now().Add(15 * time.Second)
	for {
		ready, err := messagesReady(ctx, base, "admin", "password", q.Name)
		if err == nil && ready == 1 {
			break
		}
		if time.Now().After(deadline) {
			t.Fatalf("queue %s: messages_ready=%d err=%v, want 1", q.Name, ready, err)
		}
		time.Sleep(500 * time.Millisecond)
	}

	d, ok, err := ch.Get(q.Name, true)
	if err != nil || !ok || d.MessageId != "m-1" {
		t.Fatalf("Get: ok=%v id=%q err=%v", ok, d.MessageId, err)
	}
}

func messagesReady(ctx context.Context, base, user, pass, queue string) (int, error) {
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("%s/api/queues/%%2F/%s", base, queue), nil)
	if err != nil {
		return 0, err
	}
	req.SetBasicAuth(user, pass)
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return 0, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return 0, fmt.Errorf("management API status %d", resp.StatusCode)
	}
	var body struct {
		MessagesReady int `json:"messages_ready"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
		return 0, err
	}
	return body.MessagesReady, nil
}

For Laravel, tests that use vladimir-yuldashev/laravel-queue-rabbitmq should fake the queue for unit tests and use a RabbitMQ service container for the few tests that need the real driver. The CI snippet shows service containers.

yml
# Expected, not run. Unit tests need no services; the integration job gets
# real brokers as service containers. Only the integration job pays for them.
name: tests
on: [push, pull_request]

jobs:
  unit:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-go@v5
        with: { go-version: '1.24' }
      - run: go test -race -count=1 ./...
        working-directory: go

  integration:
    runs-on: ubuntu-latest
    needs: unit            # do not start containers if the fast layer is red
    if: github.event_name == 'pull_request' || github.ref == 'refs/heads/main'
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-go@v5
        with: { go-version: '1.26' }
      # Testcontainers starts and removes the containers itself; the runner only needs Docker.
      - run: go test -tags integration -count=1 -timeout 10m ./...
        working-directory: go/integration

  laravel:
    runs-on: ubuntu-latest
    services:
      redis:
        image: redis:7
        ports: ['6379:6379']
        options: >-
          --health-cmd "redis-cli ping" --health-interval 5s --health-retries 10
    steps:
      - uses: actions/checkout@v4
      - uses: shivammathur/setup-php@v2
        with: { php-version: '8.3' }
      - run: composer install --no-interaction --prefer-dist
      - run: php artisan test --parallel
        env:
          QUEUE_CONNECTION: redis
          REDIS_HOST: 127.0.0.1

Kafka ​

Kafka tests need three explicit choices: create the topic yourself (admin API, not auto-creation), give each test its own group.id, and state where a new group starts. The Kafka consumer documentation lists auto.offset.reset with default latest, so a new group would skip records produced before it joined; franz-go documents AtStart as its default but a test should set it. The Testcontainers Kafka module (KRaft, confluentinc/confluent-local) offers Brokers(ctx); the Redpanda module offers KafkaSeedBroker(ctx). Redpanda starts faster and speaks the Kafka protocol; confirm behaviors you depend on, such as transactions, on the broker you run in production. A consumer rebalance test starts a second client in the same group while the first processes a batch, then asserts no commit is lost and duplicates are tolerated. Example expected, not run.

go
//go:build integration

package integration

import (
	"context"
	"testing"
	"time"

	"github.com/testcontainers/testcontainers-go"
	"github.com/testcontainers/testcontainers-go/modules/kafka"
	"github.com/testcontainers/testcontainers-go/modules/redpanda"
	"github.com/twmb/franz-go/pkg/kadm"
	"github.com/twmb/franz-go/pkg/kgo"
)

// expected, not run: needs a Docker daemon.
func TestKafkaUniqueTopicAndGroup(t *testing.T) {
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
	defer cancel()

	ctr, err := kafka.Run(ctx, "confluentinc/confluent-local:7.5.0", kafka.WithClusterID("test-cluster"))
	testcontainers.CleanupContainer(t, ctr)
	if err != nil {
		t.Fatal(err)
	}
	brokers, err := ctr.Brokers(ctx)
	if err != nil {
		t.Fatal(err)
	}
	roundTrip(ctx, t, brokers)
}

// Redpanda starts faster than a JVM broker and speaks the Kafka protocol; it
// is a common CI substitute, but confirm behaviours you depend on (for
// example transactions or exact error codes) against the broker you run.
func TestRedpandaUniqueTopicAndGroup(t *testing.T) {
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
	defer cancel()

	ctr, err := redpanda.Run(ctx, "docker.redpanda.com/redpandadata/redpanda:v23.3.3")
	testcontainers.CleanupContainer(t, ctr)
	if err != nil {
		t.Fatal(err)
	}
	seed, err := ctr.KafkaSeedBroker(ctx)
	if err != nil {
		t.Fatal(err)
	}
	roundTrip(ctx, t, []string{seed})
}

func roundTrip(ctx context.Context, t *testing.T, brokers []string) {
	t.Helper()
	topic, group := unique(t, "topic"), unique(t, "group")

	// Create the topic explicitly: no reliance on broker auto-creation, and
	// one partition keeps the ordering assertion trivial.
	admin, err := kgo.NewClient(kgo.SeedBrokers(brokers...))
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(admin.Close)
	if _, err := kadm.NewClient(admin).CreateTopic(ctx, 1, 1, nil, topic); err != nil {
		t.Fatal(err)
	}

	for _, v := range []string{"a", "b", "c"} {
		res := admin.ProduceSync(ctx, &kgo.Record{Topic: topic, Key: []byte("k"), Value: []byte(v)})
		if err := res.FirstErr(); err != nil {
			t.Fatal(err)
		}
	}

	// A fresh group has no committed offset. State the start position
	// explicitly: the Java client defaults to auto.offset.reset=latest and
	// would wait forever for records produced before it joined; franz-go
	// documents AtStart as its default, but a test should not rely on that.
	cl, err := kgo.NewClient(
		kgo.SeedBrokers(brokers...),
		kgo.ConsumerGroup(group),
		kgo.ConsumeTopics(topic),
		kgo.ConsumeStartOffset(kgo.NewOffset().AtStart()),
		kgo.DisableAutoCommit(),
	)
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(cl.Close)

	var got []string
	for len(got) < 3 {
		fetches := cl.PollFetches(ctx)
		if err := fetches.Err0(); err != nil {
			t.Fatal(err)
		}
		fetches.EachRecord(func(r *kgo.Record) { got = append(got, string(r.Value)) })
	}
	if want := "abc"; got[0]+got[1]+got[2] != want {
		t.Fatalf("records = %v, want %q in order", got, want)
	}
	if err := cl.CommitUncommittedOffsets(ctx); err != nil {
		t.Fatal(err)
	}
}

For Laravel with mateusjunges/laravel-kafka, unit tests fake the producer or consumer boundary and assert on the message value and headers; a real-broker test belongs in CI with a container.

Redis Streams ​

Redis Streams is the cheapest to test: miniredis is an in-process Go server that supports XADD, XGROUP CREATE, XREADGROUP, XACK, XPENDING, XCLAIM and XAUTOCLAIM (its README lists them; XINFO is partial), so stream logic runs in plain go test with no Docker. Create the group with XGROUP CREATE key group $ MKSTREAM; MKSTREAM creates the stream if absent, and BUSYGROUP means the group already exists. Use a unique stream and group per test. Run the same worker code against a real Redis in a tagged test to catch what the fake does not model, such as Lua scripts and replication. Laravel's Redis queue driver uses lists and sorted sets, not streams, so stream tests in Laravel use the Redis facade directly.

go
// Package streams is a minimal Redis Streams consumer used to show per-test
// isolation: every test creates its own stream and consumer group.
package streams

import (
	"context"
	"errors"
	"strings"

	"github.com/redis/go-redis/v9"
)

// EnsureGroup creates the group and the stream if either is missing.
// MKSTREAM makes XGROUP CREATE succeed on a stream that does not exist yet;
// BUSYGROUP means a previous run already created it, which is fine.
func EnsureGroup(ctx context.Context, rdb redis.Cmdable, stream, group string) error {
	err := rdb.XGroupCreateMkStream(ctx, stream, group, "$").Err()
	if err != nil && !strings.HasPrefix(err.Error(), "BUSYGROUP") {
		return err
	}
	return nil
}

// Handler processes one entry; a nil error means "safe to XACK".
type Handler func(ctx context.Context, id string, fields map[string]any) error

// ReadOnce reads up to count NEW entries (">") for this consumer, handles
// each, and acknowledges only the ones whose handler returned nil. A failed
// entry stays in the group's pending entries list (PEL) for later recovery.
func ReadOnce(ctx context.Context, rdb redis.Cmdable, stream, group, consumer string, count int64, h Handler) (handled int, err error) {
	return read(ctx, rdb, stream, group, consumer, ">", count, h)
}

// RecoverOwn re-reads this consumer's own pending entries (id "0"),
// the normal first step after a restart that kept the same consumer name.
func RecoverOwn(ctx context.Context, rdb redis.Cmdable, stream, group, consumer string, count int64, h Handler) (handled int, err error) {
	return read(ctx, rdb, stream, group, consumer, "0", count, h)
}

func read(ctx context.Context, rdb redis.Cmdable, stream, group, consumer, start string, count int64, h Handler) (int, error) {
	res, err := rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
		Group: group, Consumer: consumer, Streams: []string{stream, start},
		Count: count, Block: -1, // negative: do not send BLOCK, return immediately
	}).Result()
	if errors.Is(err, redis.Nil) {
		return 0, nil
	}
	if err != nil {
		return 0, err
	}
	handled := 0
	for _, s := range res {
		for _, m := range s.Messages {
			if herr := h(ctx, m.ID, m.Values); herr != nil {
				continue // leave it pending; an operator or reaper decides
			}
			if err := rdb.XAck(ctx, stream, group, m.ID).Err(); err != nil {
				return handled, err
			}
			handled++
		}
	}
	return handled, nil
}

// PendingCount is the number of delivered-but-unacknowledged entries.
func PendingCount(ctx context.Context, rdb redis.Cmdable, stream, group string) (int64, error) {
	p, err := rdb.XPending(ctx, stream, group).Result()
	if err != nil {
		return 0, err
	}
	return p.Count, nil
}
go
package streams

import (
	"context"
	"crypto/rand"
	"encoding/hex"
	"errors"
	"strings"
	"testing"

	"github.com/alicebob/miniredis/v2"
	"github.com/redis/go-redis/v9"
)

// uniqueName gives every test its own stream/group so tests never see each
// other's entries, even when they share one real Redis in CI.
func uniqueName(t *testing.T, kind string) string {
	t.Helper()
	b := make([]byte, 4)
	if _, err := rand.Read(b); err != nil {
		t.Fatal(err)
	}
	return kind + "-" + strings.ReplaceAll(strings.ToLower(t.Name()), "/", "_") + "-" + hex.EncodeToString(b)
}

// newRedis starts an in-process fake Redis; no Docker, no network port clash.
func newRedis(t *testing.T) *redis.Client {
	t.Helper()
	mr := miniredis.RunT(t) // closed automatically via t.Cleanup
	rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()})
	t.Cleanup(func() { _ = rdb.Close() })
	return rdb
}

func TestAckRemovesFromPendingAndFailureStaysPending(t *testing.T) {
	ctx := context.Background()
	rdb := newRedis(t)
	stream, group := uniqueName(t, "s"), uniqueName(t, "g")

	if err := EnsureGroup(ctx, rdb, stream, group); err != nil {
		t.Fatal(err)
	}
	if err := EnsureGroup(ctx, rdb, stream, group); err != nil {
		t.Fatalf("second EnsureGroup must tolerate BUSYGROUP: %v", err)
	}
	for _, v := range []string{"ok", "bad"} {
		if err := rdb.XAdd(ctx, &redis.XAddArgs{Stream: stream, Values: map[string]any{"v": v}}).Err(); err != nil {
			t.Fatal(err)
		}
	}

	handler := func(_ context.Context, _ string, f map[string]any) error {
		if f["v"] == "bad" {
			return errors.New("cannot process")
		}
		return nil
	}
	handled, err := ReadOnce(ctx, rdb, stream, group, "worker-1", 10, handler)
	if err != nil || handled != 1 {
		t.Fatalf("handled=%d err=%v, want 1", handled, err)
	}
	if n, _ := PendingCount(ctx, rdb, stream, group); n != 1 {
		t.Fatalf("pending = %d, want 1 (the failed entry)", n)
	}

	// Fix the "bug", restart with the same consumer name, recover the pending entry.
	handled, err = RecoverOwn(ctx, rdb, stream, group, "worker-1", 10, func(context.Context, string, map[string]any) error { return nil })
	if err != nil || handled != 1 {
		t.Fatalf("recovered=%d err=%v, want 1", handled, err)
	}
	if n, _ := PendingCount(ctx, rdb, stream, group); n != 0 {
		t.Fatalf("pending after recovery = %d, want 0", n)
	}
}

func TestTwoTestsNeverShareAGroup(t *testing.T) {
	ctx := context.Background()
	rdb := newRedis(t)
	a, b := uniqueName(t, "s"), uniqueName(t, "s")
	if a == b {
		t.Fatal("unique names collided")
	}
	if err := EnsureGroup(ctx, rdb, a, "g"); err != nil {
		t.Fatal(err)
	}
	if n, _ := rdb.Exists(ctx, b).Result(); n != 0 {
		t.Fatal("stream b must not exist")
	}
}
go
//go:build integration

package integration

import (
	"context"
	"testing"

	"github.com/redis/go-redis/v9"
	"github.com/testcontainers/testcontainers-go"
	tcredis "github.com/testcontainers/testcontainers-go/modules/redis"

	"academy/testing-messaging/streams"
)

// expected, not run: needs a Docker daemon. The same worker code that the
// miniredis unit test exercises runs here against a real Redis server.
func TestRedisStreamsAgainstRealServer(t *testing.T) {
	ctx := context.Background()
	ctr, err := tcredis.Run(ctx, "redis:7")
	testcontainers.CleanupContainer(t, ctr)
	if err != nil {
		t.Fatal(err)
	}
	uri, err := ctr.ConnectionString(ctx)
	if err != nil {
		t.Fatal(err)
	}
	opt, err := redis.ParseURL(uri)
	if err != nil {
		t.Fatal(err)
	}
	rdb := redis.NewClient(opt)
	t.Cleanup(func() { _ = rdb.Close() })

	stream, group := unique(t, "stream"), unique(t, "group")
	// XGROUP CREATE ... MKSTREAM: the group and the stream appear together.
	if err := streams.EnsureGroup(ctx, rdb, stream, group); err != nil {
		t.Fatal(err)
	}
	if err := rdb.XAdd(ctx, &redis.XAddArgs{Stream: stream, Values: map[string]any{"v": "x"}}).Err(); err != nil {
		t.Fatal(err)
	}
	n, err := streams.ReadOnce(ctx, rdb, stream, group, "c1", 10,
		func(context.Context, string, map[string]any) error { return nil })
	if err != nil || n != 1 {
		t.Fatalf("handled=%d err=%v", n, err)
	}
	t.Cleanup(func() { rdb.Del(context.Background(), stream) }) // best-effort cleanup on shared Redis
}
go
//go:build integration

package integration

import (
	"crypto/rand"
	"encoding/hex"
	"strings"
	"testing"
)

// unique returns a name no other test, and no earlier run of this test, can
// reuse: topic, queue, stream and consumer-group names all come from here.
func unique(t *testing.T, kind string) string {
	t.Helper()
	b := make([]byte, 4)
	if _, err := rand.Read(b); err != nil {
		t.Fatal(err)
	}
	name := strings.NewReplacer("/", "_", " ", "_").Replace(strings.ToLower(t.Name()))
	return kind + "." + name + "." + hex.EncodeToString(b)
}

Brokers outside this chapter's scope, such as NATS, Pulsar and SQS, also have container or emulator options (Testcontainers lists NATS and Pulsar modules); the testing layers are the same.

In production systems ​

  • Laravel's documentation states that Event::fake() disables listeners; teams that fake first and create models second see factory-created data missing UUIDs or slugs. Check order in failing tests.
  • The Testcontainers Go documentation provides separate RabbitMQ, Kafka, Redpanda and Redis modules with Run and connection helpers; one container per package with unique names is the documented-friendly pattern for cost.
  • Confluent Schema Registry's documented default is BACKWARD, which is not transitive; a three-version history needs BACKWARD_TRANSITIVE to protect consumers on the oldest schema.
  • Pact's message pacts were introduced in specification version 3; implementations vary per language, so verify the library you use supports the message format.

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

A single Laravel app dispatches jobs to a database or Redis queue. Unit tests use Queue::fake() and call handle(); one feature test runs with the sync driver to prove the whole job works against the test database. A small Go service tests its consumer with the in-memory bus and a fake clock. No containers are needed.

Modular monolith: explicit owners ​

Billing and shipping live in one deployment but own separate queues. Contract tests sit at the module boundary: the producing module's golden file is the consumer module's test input. Fakes at each port keep modules testable alone, and a unique queue prefix per module keeps shared test infrastructure from mixing them.

Microservices: contracts replace shared test environments ​

Orders publishes OrderPlaced; Billing, Shipping and Email consume it. A shared staging environment for every change is slow and flaky. Instead each consumer publishes a pact, Orders verifies all of them in its build, and a deploy gate such as Pact's can-i-deploy tool, built on the Pact “Matrix” of tested consumer and provider versions, blocks a breaking release. A registry compatibility check guards the topic. End-to-end probes remain, but few. An outbox test asserts the event row is written in the same transaction; a saga test asserts compensation after a failed step.

Distributed data: replicas, shards, and regions ​

A handler that reads a lagging replica may see a missing order and wrongly park a message. Test it with a stub repository that returns not found on the first read and found on the second, and assert retry rather than parking. Test cross-region behavior with failure injection: a publish that succeeds locally and times out remotely, and a redelivery after failover that arrives with the same business ID. Keep container tests single-region; simulate region faults with proxies.

Scaling path ​

LoadTest designExample
1xFakes, table-driven tests, golden filesOne service, one queue, suite under 10 seconds
10xAdd contracts and a few container tests per brokerSeveral consumers; CI runs containers on pull requests
100xContract gate in deploy, nightly chaos, synthetic probesMany teams; schema checks against a shared registry, canary test messages

The suite also has a cost curve: every layer you add must pay for itself in prevented incidents.

Lab ​

Go unit and contract experiments were run on this machine; the container and Laravel experiments below are expected, not run. No Docker, Compose or cluster is required for experiments 1 and 2.

1. Run the fast Go suite ​

bash
cd docs/snippets/messaging/testing-messaging/go
go test -count=1 -race ./...
# run output: ok academy/testing-messaging/msg, .../orders, .../streams (about 1 s with -race)

Read TestTransientFailureRecoversAfterBackoff: the handler waits for virtual seconds, and the test finishes in microseconds.

2. Break the code and see the tests fail ​

Edit orders/consumer.go and change if c.seen(m.ID) { to if false && c.seen(m.ID) {.

bash
go test -count=1 ./orders
# run output: FAIL TestDuplicateDeliveryHasOneEffect and TestCrashBeforeAckRedeliversWithoutDoubleEffect

Revert the edit. A test that cannot fail proves nothing.

3. Real RabbitMQ with a container ​

bash
cd docs/snippets/messaging/testing-messaging/go/integration
go test -tags integration -count=1 -run RabbitMQ ./...
# expected, not run: PASS after ~10-20 s (image pull dominates the first run); the exclusive queue is gone afterwards

4. Kafka start offset and unique group ​

bash
go test -tags integration -count=1 -run 'TestKafka|TestRedpanda' ./...
# expected, not run: records a, b, c are read in order; removing ConsumeStartOffset on a Java-style default hangs until the context times out

5. Laravel fakes ​

bash
php artisan test --filter=PlaceOrderTest
# expected, not run: 5 tests pass; the invalid-order test asserts Queue::assertNothingPushed()

Common misconceptions ​

BeliefReality
Messaging code must be tested against a real brokerMost logic is tested with fakes; use a broker for wiring
A fake and a mock are the sameA fake has working behavior; a mock verifies scripted calls
Queue::fake() runs my jobIt records pushes; call handle() to test the job
Event::fake() only recordsIt also stops listeners from running
Integration tests make contract tests unnecessaryThey check one pairing; a contract protects every consumer
Sleeping longer fixes flaky testsIt hides the race; poll a condition or use a fake
Restarting the broker isolates testsUnique names per test isolate them faster
The broker guarantees order, so ordering needs no testsRetries, replays and multiple consumers reorder arrivals
A schema registry removes the need for consumer testsIt checks schema rules, not what each consumer really reads
Chaos testing needs productionFault injection in fakes and containers catches most recovery bugs
Green CI means the DLQ worksOnly a test that fails parking proves the source is not acked

Cheat sheet ​

TopicRemember
PyramidMany fast fake tests, few container tests, fewer end-to-end
PortsSmall interface owned by the consumer; fake next to it
Fake vs mockFake has behavior; mock verifies calls
Fake clockRecord sleeps; assert the schedule, not elapsed time
Laravel queueQueue::fake() then assertPushed, assertPushedOn, assertNothingPushed
Laravel busBus::fake() then assertChained, assertBatched, assertBatchCount
Laravel eventsEvent::fake() stops listeners; create models first; except to keep some
Job testsCall handle(); use withFakeQueueInteractions(); call failed()
IdempotencySame ID twice, crash before ack, one effect
OrderingDeliver seq 2 then 1; add a property test
DLQPark failure must not ack the source
ContractsPact for consumer-driven, registry for shared topics, golden file for bytes
ContainersTagged tests, one per package, unique names, cleanup
KafkaCreate topic, unique group, explicit start offset
Redisminiredis for logic, MKSTREAM per test, real Redis for scripts
CIUnit always, containers on PRs, chaos nightly

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why prefer a fake to a mock for a publisher? Must-know ​

Answer

Answer: A fake has working behavior, so tests assert outcomes (what was published) instead of how the client was called, and survive refactoring.

2 — What does Queue::fake() not do? Must-know ​

Answer

Answer: It does not run the jobs. It records pushes; test the job by instantiating it and calling handle().

3 — Why create models before Event::fake()? Important ​

Answer

Answer: Event::fake stops listeners, so factory data that depends on model events (UUIDs, slugs) would be missing.

4 — How do you test a ten-minute backoff quickly? Must-know ​

Answer

Answer: Inject a clock whose Sleep records the duration and advances virtual time, then assert the recorded schedule.

5 — What proves a consumer survives a crash before ack? Important ​

Answer

Answer: A test that processes a message, simulates the crash so the broker redelivers, processes again, and asserts a single business effect.

6 — Why must a DLQ test cover a failing parking write? Important ​

Answer

Answer: If the consumer acks after a failed park, the only copy is lost. The test asserts an error is returned and the source is not acked.

7 — What is the difference between an integration test and a contract test? Must-know ​

Answer

Answer: An integration test exercises one producer and consumer together on a real broker; a contract test checks that a message meets the consumer's minimal expectations, without any broker.

8 — Why would a new Kafka consumer group in a test wait forever? Important ​

Answer

Answer: The Java client defaults to auto.offset.reset=latest, so a new group starts after records produced earlier. Set the start offset explicitly.

9 — How do you isolate tests that share one broker container? Important ​

Answer

Answer: Give each test a unique queue, topic or stream and its own consumer group, and clean up in t.Cleanup or tearDown.

10 — When is a Redis container needed if miniredis exists? Important ​

Answer

Answer: For behavior the fake does not model: Lua scripts, replication and failover, ACLs, and exact error semantics.

11 — Name two causes of flaky async tests and a fix for each. Must-know ​

Answer

Answer: Fixed sleeps (poll for a condition or use fakes) and shared state (unique names and cleanup).

Glossary ​

TermMeaning
Test pyramidSuite shape: many unit tests, fewer integration, very few end-to-end
PortInterface owned by the application and implemented by adapters or fakes
Test doubleAny stand-in for a production object in a test
DummyDouble that only fills a parameter
StubDouble returning canned answers
FakeDouble with a working shortcut implementation
MockDouble that verifies expected calls
SpyDouble that records calls for later assertions
In-memory publisherFake publisher that stores messages in memory
Fake clockClock whose sleeps are recorded and instant
Table-driven testOne test body run over a table of cases
Queue::fake()Laravel recorder for queued jobs
Bus::fake()Laravel recorder for dispatched jobs, chains and batches
Event::fake()Laravel recorder that also stops listeners
Notification::fake()Laravel recorder for notifications
TestcontainersLibrary family that starts throwaway containers from tests
miniredisIn-process Go implementation of a Redis server for tests
RedpandaKafka-protocol-compatible broker often used as a test container
Consumer-driven contractContract written from the consumer's needs
Pact / message pactContract format and tool; message pacts cover queues
AsyncAPISpecification describing channels, operations and message payloads
Schema registry compatibilityRules checked when registering a new schema version
Golden fileStored expected output compared byte for byte
Property-based testTest of an invariant over generated inputs
Failure injectionMaking a dependency fail on purpose in a test
Flaky testTest with nondeterministic results on the same code
Test isolationNo test can observe another test's state
Poison messageMessage that fails every time under the current consumer
Test messageSynthetic marked message sent through a real path

References ​

Built by Morteza Negahi