Skip to content

Testing Strategy & TDD: Test Pyramid vs Trophy, Test Doubles, Red-Green-Refactor, BDD, Contract Tests, Flaky Tests ​

"The test pyramid is a way of thinking about how different kinds of automated tests should be used to create a balanced portfolio." — Martin Fowler, "Test Pyramid" (martinfowler.com/bliki/TestPyramid.html)

Summary: A testing strategy answers three questions: what to test at which level (unit, integration, end-to-end), what to replace with a test double and what to run for real, and how to keep the suite fast, trustworthy and cheap to change. Test-driven development is one way to get there: write a failing test, make it pass, clean up, repeat. Focus: Test levels and sizes, the pyramid, the trophy and the honeycomb, the five test doubles (dummy, stub, spy, mock, fake) with Go and PHP examples, the London and Chicago schools, the real red-green-refactor loop (with triangulation), test naming and structure, test data (builders, factories, fixtures), database tests, hermetic and flaky tests, BDD and Gherkin, consumer-driven contract tests with Pact, coverage and mutation testing, property-based and snapshot tests, CI stages, parallelism and test impact analysis, testing in production. Learning goal: Decide for any piece of code which kind of test gives the most confidence per minute of writing and running, design the code so that test is possible, run a TDD cycle without cargo-culting it, and recognise the failure modes: mock-heavy tests that break on every refactor, flaky tests that teach the team to ignore red, and a coverage number that measures nothing.

This page is the strategy chapter. It does not re-teach the mechanics of its neighbours. Go's testing package, table-driven tests, subtests, httptest, benchmarks and fuzzing are on Testing & Benchmarking; interfaces, dependency injection and hand-written mocks in Go are on Mocking, Interfaces & Dependency Injection; testing queues, brokers and consumers (including Queue::fake) is on Testing Messaging Systems; pytest and FastAPI tests are on Testing FastAPI & pytest; the stages and runners of a pipeline are on CI/CD Pipelines; security testing in the lifecycle is on Secure SDLC & Incident Response; turning requirements into examples is on Requirements, PRDs & User Stories; the code-level craft that makes code testable is on Clean Code Principles (pure functions, functional core, imperative shell) and the smells that make tests painful are on Code Smells & Refactoring; dependency inversion, which makes substitution possible, is on SOLID and DIP; and ports and adapters at architecture level are on Clean, Hexagonal & Component Principles.

Page map ​

If you are looking forGo to
The vocabulary, the five doubles and the three shapes in three tablesEverything in one minute
Why tests exist and the three beliefs to drop firstWhy testing strategy exists
Fowler, Beck, Meszaros, Google, Dodds, Spotify, Pact: who said whatWhere it comes from
Unit, integration, component, end-to-end, acceptance, smoke, regression; Google small, medium, largeTest levels and sizes
Pyramid versus trophy versus honeycombTest shapes
Dummy, stub, spy, mock, fake with Go and PHP codeTest doubles
London versus Chicago, mockist versus classicist, sociable versus solitaryThe two schools
Red, green, refactor, test-first, triangulation, transformation priority premiseThe TDD loop
Arrange act assert, naming, one assertion per concept, FIRST, table-driven testsAnatomy of a good test
Test data builders, object mothers, Laravel factories, fixturesTest data
RefreshDatabase, DatabaseTransactions, testcontainers, in-memory fakes versus real dependenciesDatabase tests
Non-determinism, quarantine, retries, hermetic testsFlaky tests
Gherkin, Cucumber, Behat, godog, specification by example, ATDDBDD
Pact, consumer-driven contracts, can-i-deployContract tests
Line, branch and path coverage, coverage targetsCoverage
Infection, go-mutesting, gremlinsMutation testing
rapid, testing/quick, fuzzing, ErisProperty-based tests
Golden files and snapshotsSnapshot tests
Canary, feature flags, shift left, testing in productionTesting in production
CI stages, test parallelism, test impact analysisCI and speed
Laravel Feature and Unit tests, Pest versus PHPUnitLaravel testing
Designing code so it can be testedDesign for testability
The test review checklistReview checklist
Slow suite, brittle mocks, flaky suite, ice-cream coneSolving the classic problems
Which test for which situationChoosing
One process to many servicesIn architecture
A hands-on session in Go and LaravelLab
Wrong beliefs, cheat sheet, interview questions, every termMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

Test levels, in one table. The names are murky (Fowler says so himself), so the last column gives the measurable version Google uses.

LevelIn plain wordsTiny exampleGoogle size
Unit testOne small piece of code, fast, no outside worldAdd("1,2") == 3Small
Integration testOur code together with something it depends onRepository against a real PostgreSQLMedium
Component testOne deployable component, its neighbours replacedA service with its own database, other services stubbedMedium
Contract testThe shape of the messages between two partiesConsumer expects {"rate": number}Small or medium
End-to-end testThe whole system through its real entry pointBrowser buys an item on stagingLarge
Acceptance testA business rule stated by the customer, automated"Gold customers ship free from 50.00"Any size
Smoke testA handful of checks that the deployment is aliveGET /health then log inLarge (a few)
Regression testA test that pins a bug that was fixedThe failing input from the incidentAny size

The five test doubles (Meszaros). Every row is unpacked in Test doubles.

DoubleDoesYou assert onExample
DummyFills a parameter, is never usedNothingA mailer passed to a function that rejects bad input first
StubReturns canned answersThe result or stateA gateway that always declines
SpyA stub that also records callsThe recording, afterwardsA mailer that remembers what it was asked to send
MockHas expectations and fails when they are violatedThe interaction itself"Charge exactly once with these arguments"
FakeA real but simplified implementationStateAn in-memory repository

The three shapes and the two schools.

NameManyFewWho and when
Test pyramidUnit testsEnd-to-end testsMike Cohn; Fowler's bliki entry is dated 1 May 2012
Testing trophyIntegration tests (plus static analysis)Unit and end-to-end testsKent C. Dodds, tweet of 6 February 2018
Testing honeycombIntegration tests of one serviceImplementation-detail tests, integrated testsSpotify, post of 11 January 2018
London school (mockist)Solitary tests with mocks for every collaboratorReal collaboratorsEarly XP adopters in London
Chicago or Detroit school (classicist)Real objects, doubles only where awkwardMocksThe original XP practice at C3 in Detroit

Why testing strategy exists ​

Tests exist so that change is cheap. Fowler describes self-testing code as the ability to "invoke a single command that executes the tests" and be "confident that these tests will illuminate any bugs hiding in your code", a "bug detector" built together with the system. The whole value of a suite is the speed and trustworthiness of that detector. A strategy is the decision about where to spend a finite budget of writing time, running time and maintenance time.

Pull one wayPull the other way
Fast feedback (many small tests)Realism (few large tests that look like production)
Isolation (doubles everywhere)Confidence that the parts really fit (real collaborators)
Precise failures (one assertion, one cause)Few tests to maintain (broad tests that touch much)
Refactoring freedom (test behaviour)Detecting wiring mistakes (test interactions)
Zero flakiness (no network, no clock)Catching what only happens in a real environment

An everyday picture. A restaurant kitchen. The cook tastes each sauce while making it (unit tests: instant, specific). The sous-chef plates one full dish and checks it before service (integration: parts together). Once a night the owner eats a whole three-course meal through the dining room (end-to-end: slow, expensive, tells you the whole experience works). If the owner had to taste everything, service would never start; if only the sauces were tasted, nobody would notice the plate arrives cold. The skill is the mix, and a thermometer that sometimes lies (a flaky test) is worse than none, because the cooks learn to ignore it.

Three common misunderstandings, up front ​

  1. "More tests means a better suite." Each test is baggage. Ham Vocke's practical pyramid article puts it plainly: every test "doesn't come for free", because writing, reading and running it all take time. A suite of 5,000 slow, overlapping, brittle tests is worse than 800 good ones.
  2. "TDD means writing all the tests first." Kent Beck's own description says the opposite: write a list of scenarios, then turn exactly one item into a test, make it pass, optionally refactor, and repeat. He lists "convert all the items on the Test List into concrete tests" as a mistake.
  3. "A mock is a kind of stub, and mocking everything is the safe default." A mock verifies behaviour (calls), a stub supplies answers; mixing them up produces tests that fail whenever you refactor and pass while the real integration is broken. The strategy question is always: what is the cheapest test that would fail if this were wrong?

Where it comes from ​

text
     Year   Who / what                                                  What it gave us
1    1994-95 Beck writes SUnit (1994) and demos TDD to Ward Cunningham (Oct 1995), by his own account in Canon TDD; Fowler dates TDD to the late 1990s   "unit test" as programmer-written test; TDD
2    2006   Meszaros, via Fowler "Test Double" (17 Jan 2006)            the vocabulary: dummy, fake, stub, spy, mock
3    2010   Google Testing Blog "Test Sizes" (13 Dec 2010)              small, medium, large defined by resources, not by name
4    2011   Fowler "Contract Test" (12 Jan 2011)                        contract tests keep doubles honest
5    2012   Fowler "Test Pyramid" (1 May 2012), "Test Coverage" (17 Apr 2012)  the portfolio picture; coverage as a finder, not a target
6    2013   Robert C. Martin, Transformation Priority Premise (27 May 2013)    a heuristic for picking the next simplest code change
7    2016   Google "Flaky Tests at Google" (27 May 2016)                1.5 % flaky runs; quarantine and rerun policies
8    2018   Practical Test Pyramid (Vocke, Fowler site); Spotify honeycomb (11 Jan 2018); Dodds trophy tweet (6 Feb 2018)   the pyramid in practice, and the two challengers
9    2021   Fowler "On the Diverse And Fantastical Shapes of Testing" (2 Jun 2021)   the shapes debate is mostly a vocabulary problem
10   2023   Beck "Canon TDD" (11 Dec 2023)                              the definition of TDD, written to stop strawman critiques

The dates in rows 2 to 10 are the dates printed on the saved pages (see References); row 1 gives Beck's own dating ("I wrote SUnit in 1994", TDD demoed in October 1995) next to Fowler's looser "developed by Kent Beck in the late 1990's as part of Extreme Programming".

What each source actually says, from the pages saved for this chapter:

  • Fowler, Test Pyramid: "you should have many more low-level UnitTests than high level BroadStackTests running through a GUI". UI-driven tests are "brittle, expensive to write, and time consuming to run". A footnote adds the escape hatch: if the high-level tests are fast, reliable and cheap to modify, "then lower-level tests aren't needed". The pyramid is credited to Mike Cohn.
  • Fowler, Test Double: "Test Double is a generic term for any case where you replace a production object for testing purposes", with Gerard Meszaros's five kinds.
  • Fowler, Shapes of Testing (2021): the honeycomb and trophy advocates "criticize the excessive use of mocks", so their "unit test" is what Fowler would call a solitary unit test and their "integration test" is what he would call a sociable one; "this makes the pyramid versus honeycomb discussion moot". He quotes Justin Searls: "People love debating what percentage of which type of tests to write, but it's a distraction."
  • Dodds, Testing Trophy: the trophy was introduced for JavaScript front ends; he "never considered whether it applied to microservices or even backend services", and the guiding line is "The more your tests resemble the way your software is used, the more confidence they can give you."
  • Spotify, Testing of Microservices: "A more fitting way of structuring our tests for Microservices would be the Testing Honeycomb"; focus on integration tests, "a few Implementation Detail Tests and even fewer Integrated Tests (ideally none)". Spotify's page returns 403 to plain curl, so the saved copy and the reference link come from the Internet Archive.
  • Google, Test Sizes: small tests may use no network, no database, no file system and no sleeps (60 seconds); medium may use localhost and a database (300 seconds); large may use external systems (900+ seconds).
  • Beck, Canon TDD: five steps (test list, one test, make it pass, optionally refactor, repeat) and a list of named mistakes.

The rest of the page applies these in order: levels and shapes first, then doubles and schools, then the TDD loop and the anatomy of a test, then the supporting practices (data, databases, flakiness, BDD, contracts, coverage, mutation, properties, snapshots), then delivery (production, CI) and the framework specifics.

The concept catalogue ​

Each block follows the same order: plain words, the misunderstanding, the definition, a timeline, real scenarios, then Go and PHP/Laravel. Code lives once under docs/snippets/design/testing-strategy-tdd/ and is imported here.

Test levels and sizes: unit, integration, component, end-to-end, acceptance, smoke, regression Must-know ​

In plain words: a level says how much of the system one test touches; a size says how many resources it may use. Levels are arguments, sizes can be enforced.

Common misunderstanding: "Everyone means the same thing by unit test and integration test." Fowler's "Unit Test" entry recalls a testing expert who said "in the first morning of my training course I cover 24 different definitions of unit test", and Dodds quotes the same line. Ask what is meant before agreeing on a ratio.

Definition: the terms as used on this page.

TermMeaning used hereTypical double policy
Unit testFast, programmer-written test of a small unit (a function, a class, a few related classes)Pure code needs none; slow or external collaborators replaced
Integration testChecks that independently developed pieces work when connected; Fowler notes it "can be more effectively done with a narrower scope" than people assumeReal database or real HTTP handler, outside services replaced
Component testA whole deployable component through its public interface, its neighbours replacedNeighbours stubbed or faked, own database real
End-to-end testThe full system through its real entry point (browser, public API)Nothing replaced except third parties you must not call
Acceptance testExpresses a requirement in the customer's words and passes only when it is deliveredChosen per level; often component or end-to-end
Smoke testA tiny set of checks right after deployment: is it alive, can the main path runNone; runs against the deployed build
Regression testAny test added because a bug escaped; it keeps the bug deadSmallest level that reproduces the bug
Subcutaneous testActs through the service layer, skipping the UI (Fowler)UI absent, rest real
Contract testChecks the messages between two parties against a shared contractSee Contract tests

Google's sizes (Test Sizes, 13 December 2010) turn the vague names into resource limits:

FeatureSmallMediumLarge
Network accessNolocalhost onlyYes
DatabaseNoYesYes
File system accessNoYesYes
External systemsNoDiscouragedYes
Multiple threadsNoYesYes
Sleep statementsNoYesYes
Time limit (seconds)60300900+

The post equates a small test with a unit test, a large test with an end-to-end or system test and a medium test with a test "that ensure that two tiers in an application can communicate properly (often called an integration test)". Its main advantage is that tools can police the limits, and it also requires that "tests can be run in any order", which forces isolation and makes parallel runs possible.

Timeline of a regression test (a bug report arrives):

text
     Step  Who        What happens
1    Mon   Support    "Order total is wrong when the coupon is 100 percent"
2    Mon   Dev        reproduces it with a failing unit test: Total(coupon=100) = -0.01, want 0
3    Mon   Dev        fixes the rounding; the test goes green
4    Mon   CI         the test now runs on every commit: the bug cannot return silently
5    Fri   Dev B      refactors the coupon code; the regression test catches a slip in review

Real scenarios: a payment rounding bug pinned by a table row; a "login works" smoke test after every deploy; a component test that starts a service with its own PostgreSQL and a stubbed pricing service; an acceptance test written by product and developer together (BDD).

Go and PHP: in Go a size is a convention, not a type; the usual tools are go test -short with a skip in medium tests, build tags, or directories. The module's hermetic.SkipInShort helper does the first one and the contract tests use it.

go
func SkipInShort(t testing.TB) {
	t.Helper()
	if testing.Short() {
		t.Skip("skipping medium test in -short mode")
	}
}
bash
go test -short ./...        # small tests only: seconds, run on every save
go test ./...               # small and medium: run on every push

In PHP, PHPUnit test suites and groups play the same role (--testsuite, #[Group]), and Laravel's default tests/Unit versus tests/Feature split is a size split in practice (see Laravel testing).

Test shapes: pyramid, trophy, honeycomb Must-know ​

In plain words: a shape is a picture of how many tests of each level a healthy portfolio has. Pyramid: lots of unit tests. Trophy and honeycomb: mostly integration tests.

Common misunderstanding: "The pyramid is outdated; integration tests are the new unit tests." Fowler's 2021 article argues the disagreement is mostly about the meaning of the words: the honeycomb and trophy camp mean by "unit test" a solitary test full of mocks and by "integration test" what the pyramid camp calls a sociable unit test. Both camps want fast, reliable tests that fail for useful reasons.

Definition:

Pyramid (Cohn, Fowler)E2E / UIservice / APIunit (many)fast and cheap at the baseTrophy (Dodds)E2Eintegration (most)unitstatic (types, lint)confidence per hour spentHoneycomb (Spotify)integrated (ideally none)integration (focus)service + its own DB + contractsimplementation detailsmall services, interactions matter
ShapeOriginBiggest layerAdviceCaveat from its author or critics
Test pyramidMike Cohn (Succeeding with Agile), Fowler bliki 2012, Vocke's Practical Test PyramidUnit testsPush tests as far down as they can go; if a high-level test finds a bug and no lower-level test fails, write the lower-level oneFootnote: if high-level tests are fast, reliable and cheap to change, lower ones are not needed
Testing trophyKent C. Dodds, 2018, from Guillermo Rauch's tweet "Write tests. Not too many. Mostly integration."Integration tests, with static analysis (types, linters) as the baseMaximise confidence per hour; tests should resemble how the software is usedDesigned for JavaScript front ends and monoliths, not microservices
Testing honeycombSpotify, 2018Integration tests of one serviceVerify the service "in a more isolated fashion while focusing on the interaction points"; avoid tests that pass or fail on another system's correctnessWritten for small services where interactions are the complex part

Timeline of a shape decision (a team inherits an ice-cream cone):

text
     Step  Who        What happens
1    Week 1  Team     inventory: 40 browser tests (50 min), 300 unit tests (20 s), nothing in between
2    Week 2  Team     every failure is a 50-minute wait; half of the red runs are flaky
3    Week 3  Team     adds 120 API-level component tests against a real database (4 min)
4    Week 5  Team     deletes 30 of the 40 browser tests that the API tests now cover
5    Week 8  Team     browser tests: 10 smoke journeys (6 min); feedback on most changes in under 5 min

Real scenarios: a Laravel monolith whose HTTP feature tests with RefreshDatabase are the workhorse (Laravel's own docs say "most of your tests should be feature tests"); a Go service where table-driven unit tests cover pure pricing code and httptest plus a real PostgreSQL cover the handlers; a microservice fleet where Pact contracts replace the shared staging environment.

Go and PHP: the shape is not a framework feature. In Go, pure functions and the functional core (Clean Code) give many cheap unit tests, while handlers and repositories get a smaller number of integration tests with net/http/httptest and a real database. In Laravel the default test scaffold already leans to the trophy: Feature tests boot the application and hit the database.

Test doubles: dummy, stub, spy, mock, fake Must-know ​

In plain words: a double stands in for a collaborator you cannot or do not want to run for real: a payment API, an e-mail server, a slow database. The five kinds differ in what they do with the calls they receive.

Common misunderstanding: "Mock is the word for any fake object." In Meszaros's vocabulary, which Fowler's "Test Double" entry spreads, a mock is one specific kind: "pre-programmed with expectations which form a specification of the calls they are expected to receive". Calling every double a mock hides the real decision (state versus behaviour verification).

Definition (Meszaros, via Fowler):

System under testcalls its collaboratorsDummyFills a parameter list; any call is a bug. Verifies nothing.StubReturns canned answers or errors to steer the path. You assert on state.SpyA stub that records how it was called. You assert on the recording afterwards.MockHolds expectations (calls, arguments, counts); the test fails if they are not met.FakeA working shortcut (in-memory repo, local queue). Needs its own contract test.
DoubleFowler's wordingVerifiesTypical useDanger
Dummy"passed around but never actually used"; fills parameter listsNothingA required argument irrelevant to this testHides that the unit has too many dependencies
Stub"canned answers to calls made during the test"Result or stateSteer the code down a path: decline, timeout, empty listStubs everywhere make tests restate the implementation
Spy"stubs that also record some information based on how they were called"Recording, after the actOutgoing effects: mail sent, event publishedAsserting on incidental calls
Mock"pre-programmed with expectations"; can "throw an exception if they receive a call they don't expect"The interactionThe interaction is the requirement: charge once with these argumentsCouples the test to the call structure; breaks on refactors
Fake"working implementations, but usually take some shortcut"StateIn-memory repository, local queue, SQLite for a unit-level runThe fake drifts from the real thing unless a contract test guards it

Timeline of the same use case under each double (placing an order: charge, save, mail):

text
     Test                                    Doubles used                 Asserts on
1    rejects total 0                         dummy gateway, mailer, audit  returned error only; any call would panic
2    card declined stores nothing            stub gateway (error), fake repo   error wraps cause; repo is empty
3    success sends one confirmation          stub gateway, spy mailer      spy recorded exactly one message
4    charges exactly once, right arguments   mock gateway                  mock fails on a wrong call or a missing call
5    placed order can be found               stub gateway, fake repo       fake returns the saved order

Real scenarios: a payment gateway stubbed to decline; an outbound e-mail spied on; a repository replaced by an in-memory fake in unit tests and run against a real database in a contract test; a mock used where "exactly one charge" is the business rule (double charging is a real incident, so the interaction matters).

Go: the module's doubles package has one Service.Place and all five doubles, each hand-written (Go's culture prefers small interfaces and hand-written doubles; generated mocks are covered on Mocking, Interfaces & DI). The use case:

go
// Package doubles shows the five kinds of test double (Meszaros) around one
// small use case: placing an order.
package doubles

import (
	"errors"
	"fmt"
)

// Order is the data the use case works on. Money is integer cents.
type Order struct {
	ID    string
	Email string
	Total int64
}

// PaymentGateway charges a customer. The real one calls a payment provider.
type PaymentGateway interface {
	Charge(orderID string, cents int64) (receipt string, err error)
}

// Mailer sends a message. The real one talks to SMTP or an API.
type Mailer interface {
	Send(to, subject string) error
}

// OrderRepo stores orders. The real one talks to a database.
type OrderRepo interface {
	Save(o Order) error
	Find(id string) (Order, bool)
}

// Audit records what happened, for operators.
type Audit interface {
	Log(msg string)
}

// ErrInvalidTotal is returned when the order total is not positive.
var ErrInvalidTotal = errors.New("order total must be positive")

// Service places orders.
type Service struct {
	gateway PaymentGateway
	repo    OrderRepo
	mailer  Mailer
	audit   Audit
}

// NewService wires the collaborators. All four are required.
func NewService(g PaymentGateway, r OrderRepo, m Mailer, a Audit) *Service {
	return &Service{gateway: g, repo: r, mailer: m, audit: a}
}

// Place validates, charges, stores and confirms an order. It returns the
// payment receipt. A failed charge stores nothing and sends nothing.
func (s *Service) Place(o Order) (string, error) {
	if o.Total <= 0 {
		return "", ErrInvalidTotal
	}
	receipt, err := s.gateway.Charge(o.ID, o.Total)
	if err != nil {
		return "", fmt.Errorf("charge order %s: %w", o.ID, err)
	}
	if err := s.repo.Save(o); err != nil {
		return "", fmt.Errorf("save order %s: %w", o.ID, err)
	}
	// A confirmation e-mail is best effort: the order is already paid.
	if err := s.mailer.Send(o.Email, "Order "+o.ID+" confirmed"); err != nil {
		s.audit.Log("mail failed for " + o.ID)
	}
	s.audit.Log("placed " + o.ID)
	return receipt, nil
}

// MemRepo is an in-memory OrderRepo. It is a real, working implementation,
// which makes it a fake when used in tests.
type MemRepo struct {
	orders map[string]Order
}

// NewMemRepo returns an empty MemRepo.
func NewMemRepo() *MemRepo { return &MemRepo{orders: map[string]Order{}} }

// Save stores or replaces an order by ID.
func (r *MemRepo) Save(o Order) error {
	if o.ID == "" {
		return errors.New("order has no ID")
	}
	r.orders[o.ID] = o
	return nil
}

// Find returns the order with the given ID.
func (r *MemRepo) Find(id string) (Order, bool) {
	o, ok := r.orders[id]
	return o, ok
}

The five doubles and the tests that use them. Note how each test names the double's role in a comment, and how the dummies panic if touched:

go
package doubles

import (
	"errors"
	"testing"
)

// --- Dummy: passed around, never used. It panics if anything calls it. ---

type dummyGateway struct{}

func (dummyGateway) Charge(string, int64) (string, error) { panic("dummy gateway used") }

type dummyMailer struct{}

func (dummyMailer) Send(string, string) error { panic("dummy mailer used") }

type dummyAudit struct{}

func (dummyAudit) Log(string) { panic("dummy audit used") }

// --- Stub: canned answers, no memory of how it was called. ---

type stubGateway struct {
	receipt string
	err     error
}

func (s stubGateway) Charge(string, int64) (string, error) { return s.receipt, s.err }

// --- Spy: a stub that also records how it was called. ---

type spyMailer struct {
	sent []string // "to|subject"
	err  error
}

func (s *spyMailer) Send(to, subject string) error {
	s.sent = append(s.sent, to+"|"+subject)
	return s.err
}

type spyAudit struct{ lines []string }

func (s *spyAudit) Log(msg string) { s.lines = append(s.lines, msg) }

// --- Mock: pre-programmed expectations, checked by Verify. ---

type mockGateway struct {
	t        *testing.T
	wantID   string
	wantCent int64
	calls    int
}

func (m *mockGateway) Charge(id string, cents int64) (string, error) {
	m.calls++
	if id != m.wantID || cents != m.wantCent {
		m.t.Errorf("Charge(%q, %d), want Charge(%q, %d)", id, cents, m.wantID, m.wantCent)
	}
	return "r-mock", nil
}

func (m *mockGateway) Verify() {
	m.t.Helper()
	if m.calls != 1 {
		m.t.Errorf("Charge called %d times, want exactly 1", m.calls)
	}
}

// Dummy: the validation branch never touches a collaborator.
func TestPlace_InvalidTotal_UsesOnlyDummies(t *testing.T) {
	svc := NewService(dummyGateway{}, NewMemRepo(), dummyMailer{}, dummyAudit{})
	if _, err := svc.Place(Order{ID: "o-1", Total: 0}); !errors.Is(err, ErrInvalidTotal) {
		t.Fatalf("err = %v, want ErrInvalidTotal", err)
	}
}

// Stub: force the failure path with a canned error; verify state, not calls.
func TestPlace_ChargeFails_StoresNothing(t *testing.T) {
	declined := errors.New("card declined")
	repo := NewMemRepo()
	svc := NewService(stubGateway{err: declined}, repo, dummyMailer{}, dummyAudit{})

	_, err := svc.Place(Order{ID: "o-2", Email: "a@example.com", Total: 500})

	if !errors.Is(err, declined) {
		t.Fatalf("err = %v, want it to wrap %v", err, declined)
	}
	if _, found := repo.Find("o-2"); found {
		t.Error("order was saved although the charge failed")
	}
}

// Spy: the confirmation mail is an outgoing effect, so record and inspect it.
func TestPlace_Success_SendsOneConfirmation(t *testing.T) {
	mail := &spyMailer{}
	audit := &spyAudit{}
	svc := NewService(stubGateway{receipt: "r-1"}, NewMemRepo(), mail, audit)

	receipt, err := svc.Place(Order{ID: "o-3", Email: "a@example.com", Total: 500})

	if err != nil || receipt != "r-1" {
		t.Fatalf("Place = (%q, %v), want (r-1, nil)", receipt, err)
	}
	if len(mail.sent) != 1 || mail.sent[0] != "a@example.com|Order o-3 confirmed" {
		t.Errorf("sent = %v", mail.sent)
	}
}

// A mail failure is logged, not returned: the spy lets us see that decision.
func TestPlace_MailFails_OrderStillPlaced(t *testing.T) {
	mail := &spyMailer{err: errors.New("smtp down")}
	audit := &spyAudit{}
	repo := NewMemRepo()
	svc := NewService(stubGateway{receipt: "r-1"}, repo, mail, audit)

	if _, err := svc.Place(Order{ID: "o-4", Email: "a@example.com", Total: 500}); err != nil {
		t.Fatalf("Place failed: %v", err)
	}
	if _, found := repo.Find("o-4"); !found {
		t.Error("order not saved")
	}
	if len(audit.lines) != 2 || audit.lines[0] != "mail failed for o-4" {
		t.Errorf("audit = %v", audit.lines)
	}
}

// Mock: the interaction itself is the requirement (charge exactly once, with
// exactly these arguments), so behaviour verification is justified here.
func TestPlace_ChargesExactlyOnce(t *testing.T) {
	gw := &mockGateway{t: t, wantID: "o-5", wantCent: 1250}
	svc := NewService(gw, NewMemRepo(), &spyMailer{}, &spyAudit{})

	if _, err := svc.Place(Order{ID: "o-5", Email: "a@example.com", Total: 1250}); err != nil {
		t.Fatal(err)
	}
	gw.Verify()
}

// Fake: MemRepo really stores and finds orders, so the test asserts state.
func TestPlace_Success_OrderIsFindable(t *testing.T) {
	repo := NewMemRepo()
	svc := NewService(stubGateway{receipt: "r-1"}, repo, &spyMailer{}, &spyAudit{})

	if _, err := svc.Place(Order{ID: "o-6", Email: "a@example.com", Total: 700}); err != nil {
		t.Fatal(err)
	}
	got, found := repo.Find("o-6")
	if !found || got.Total != 700 {
		t.Errorf("Find(o-6) = (%+v, %v)", got, found)
	}
}

// repoContract is the contract every OrderRepo must satisfy. Running it
// against the fake (here) and against the real repository (in an integration
// test) is what keeps the fake honest.
func repoContract(t *testing.T, newRepo func() OrderRepo) {
	t.Run("find after save", func(t *testing.T) {
		r := newRepo()
		if err := r.Save(Order{ID: "x", Total: 1}); err != nil {
			t.Fatal(err)
		}
		if got, ok := r.Find("x"); !ok || got.Total != 1 {
			t.Errorf("Find = (%+v, %v)", got, ok)
		}
	})
	t.Run("unknown id is not found", func(t *testing.T) {
		if _, ok := newRepo().Find("nope"); ok {
			t.Error("found an order that was never saved")
		}
	})
	t.Run("save without id is rejected", func(t *testing.T) {
		if err := newRepo().Save(Order{}); err == nil {
			t.Error("expected an error for an empty ID")
		}
	})
}

func TestMemRepo_SatisfiesRepoContract(t *testing.T) {
	repoContract(t, func() OrderRepo { return NewMemRepo() })
}

PHP (PHPUnit 12 and Laravel): PHPUnit's createStub() returns a stub and createMock() returns a mock whose expects() are verified; a double with no configuration is a dummy. Laravel adds $this->mock(...), $this->spy(...) and $this->partialMock(...) on top of Mockery, and fakes for facades (Http::fake, Queue::fake, Mail::fake; messaging fakes are on Testing Messaging). The same use case in PHP:

php
<?php

declare(strict_types=1);

namespace App\Orders;

use InvalidArgumentException;
use Throwable;

final class OrderService
{
    public function __construct(
        private readonly PaymentGateway $gateway,
        private readonly OrderRepository $repository,
        private readonly Mailer $mailer,
        private readonly Audit $audit,
    ) {
    }

    /** Validates, charges, stores and confirms an order; returns the receipt. */
    public function place(Order $order): string
    {
        if ($order->totalCents <= 0) {
            throw new InvalidArgumentException('order total must be positive');
        }

        $receipt = $this->gateway->charge($order->id, $order->totalCents);
        $this->repository->save($order);

        try {
            $this->mailer->send($order->email, "Order {$order->id} confirmed");
        } catch (Throwable) {
            // Best effort: the order is already paid.
            $this->audit->log("mail failed for {$order->id}");
        }
        $this->audit->log("placed {$order->id}");

        return $receipt;
    }
}
php
<?php

declare(strict_types=1);

namespace Tests\Unit;

use App\Orders\Audit;
use App\Orders\Mailer;
use App\Orders\Order;
use App\Orders\OrderRepository;
use App\Orders\OrderService;
use App\Orders\PaymentGateway;
use InvalidArgumentException;
use PHPUnit\Framework\TestCase;
use RuntimeException;

/** The five Meszaros doubles in PHPUnit 12 terms (createStub / createMock). */
final class OrderServiceTest extends TestCase
{
    public function test_invalid_total_uses_only_dummies(): void
    {
        // Dummy: an unconfigured stub that is passed along and never called.
        $service = new OrderService(
            $this->createStub(PaymentGateway::class),
            new InMemoryOrderRepository(),
            $this->createStub(Mailer::class),
            $this->createStub(Audit::class),
        );

        $this->expectException(InvalidArgumentException::class);
        $service->place(new Order('o-1', 'a@example.com', 0));
    }

    public function test_declined_charge_stores_nothing(): void
    {
        // Stub: a canned answer, here an exception.
        $gateway = $this->createStub(PaymentGateway::class);
        $gateway->method('charge')->willThrowException(new CardDeclined('card declined'));
        $repository = new InMemoryOrderRepository(); // Fake

        $service = new OrderService($gateway, $repository, $this->createStub(Mailer::class), $this->createStub(Audit::class));

        // A dedicated exception class: PHPUnit's own failure exceptions extend
        // RuntimeException, so catching RuntimeException around fail() would
        // swallow a real test failure.
        $declined = null;
        try {
            $service->place(new Order('o-2', 'a@example.com', 500));
        } catch (CardDeclined $e) {
            $declined = $e;
        }

        $this->assertNotNull($declined, 'the decline should propagate');
        $this->assertNull($repository->find('o-2'));
    }

    public function test_success_sends_one_confirmation(): void
    {
        // Spy: a hand-written double that records calls; assert afterwards.
        $mailer = new SpyMailer();
        $gateway = $this->createStub(PaymentGateway::class);
        $gateway->method('charge')->willReturn('r-1');

        $service = new OrderService($gateway, new InMemoryOrderRepository(), $mailer, $this->createStub(Audit::class));
        $receipt = $service->place(new Order('o-3', 'a@example.com', 500));

        $this->assertSame('r-1', $receipt);
        $this->assertSame([['a@example.com', 'Order o-3 confirmed']], $mailer->sent);
    }

    public function test_charges_exactly_once_with_these_arguments(): void
    {
        // Mock: expectations are part of the test; PHPUnit verifies them.
        $gateway = $this->createMock(PaymentGateway::class);
        $gateway->expects($this->once())
            ->method('charge')
            ->with('o-5', 1250)
            ->willReturn('r-mock');

        $service = new OrderService($gateway, new InMemoryOrderRepository(), new SpyMailer(), $this->createStub(Audit::class));
        $service->place(new Order('o-5', 'a@example.com', 1250));
    }

    public function test_placed_order_is_findable_in_the_fake(): void
    {
        $repository = new InMemoryOrderRepository();
        $gateway = $this->createStub(PaymentGateway::class);
        $gateway->method('charge')->willReturn('r-1');

        (new OrderService($gateway, $repository, new SpyMailer(), $this->createStub(Audit::class)))
            ->place(new Order('o-6', 'a@example.com', 700));

        $this->assertSame(700, $repository->find('o-6')?->totalCents);
    }
}

final class CardDeclined extends RuntimeException
{
}

/** Fake: a real, working repository that keeps orders in an array. */
final class InMemoryOrderRepository implements OrderRepository
{
    /** @var array<string, Order> */
    private array $orders = [];

    public function save(Order $order): void
    {
        $this->orders[$order->id] = $order;
    }

    public function find(string $id): ?Order
    {
        return $this->orders[$id] ?? null;
    }
}

final class SpyMailer implements Mailer
{
    /** @var list<array{string, string}> */
    public array $sent = [];

    public function send(string $to, string $subject): void
    {
        $this->sent[] = [$to, $subject];
    }
}

PHP syntax of all PHP files was checked with php -l; the PHPUnit tests were not run because no Composer project or PHPUnit is installed in this environment (stated again in Lab).

Fakes need a contract. A fake is only useful while it behaves like the real thing. The repoContract function in doubles_test.go runs the same three checks against any OrderRepo; here it runs against MemRepo, and a real project runs it again against the PostgreSQL repository in an integration test. Fowler's "Contract Test" entry states the same idea for external services: continue running tests against the double, and "in addition to periodically run a separate set of contract tests" that check the double matches reality.

The two schools: London versus Chicago, mockist versus classicist Must-know ​

In plain words: one school replaces every collaborator and checks the calls between objects; the other uses real collaborators and checks the outcome.

Common misunderstanding: "One of them is correct." Fowler's "Mocks Aren't Stubs" explains both as workable styles and lists the consequences of each; the practical answer is to pick per situation, with a default.

Definition:

AxisClassical (also called Detroit, or Chicago school in some texts)Mockist (London school)
Collaborators"use real objects if possible and a double if it's awkward to use the real thing""always use a mock for any object with interesting behavior"
VerificationState verification: assert on the outcomeBehaviour verification: assert on the calls
Unit test kind (Jay Fields)Sociable: real collaborators run tooSolitary: all collaborators replaced
Design pressureTests survive refactors inside the cluster; may need more set-upDrives out interfaces and collaborator roles; tests restate the call graph
Typical weaknessA fault in a collaborator fails many testsTests pass while the real wiring is broken; refactors break tests

Fowler's "Mocks Aren't Stubs" names the two styles "classical" (classicist) and "mockist", and notes that "Detroit" is used for classical and "London" for mockist, because XP was developed at C3 in Detroit and the mockist style grew among early XP adopters in London. Some texts say "Chicago school" for the classical side; that label is not in any saved source, so it is mentioned only as a name you may meet, with no attribution.

Timeline of the same test written both ways (order price with a discount rule and a customer):

text
     Step  Classical (sociable)                          Mockist (solitary)
1    build real Order, real Customer(gold)               build real Order, mock Customer
2    act: order.Price()                                  expect customer.discount() once, returning 10
3    assert: price == 90                                 act: order.Price(); verify the mock was called
4    refactor: Order asks Customer a new way             the test fails: the expected call is gone
5    test still passes (behaviour unchanged)             rewrite the expectation (behaviour unchanged)

Real scenarios: domain logic (prices, rules, state machines) fits the classical style well because the collaborators are small and deterministic; code at an architectural boundary (an application service calling a payment gateway, a mailer, a queue) fits behaviour verification for the one interaction that matters.

What to do: Vocke's practical article says "it's not important to decide if you go for solitary or sociable unit tests. Writing automated tests is what's important." A workable default: sociable tests inside a module, doubles at the module boundary, a mock only where the call itself is the requirement.

Go and PHP: Go's small interfaces at the consumer (DIP) make boundary doubles cheap; Go projects overwhelmingly lean classical, with hand-written spies and fakes. PHP's PHPUnit and Mockery make mockist style easy (expects($this->once())), which is why the temptation to over-mock is bigger there; Laravel's own testing docs lean on fakes and the real container.

The TDD loop: red, green, refactor, test-first, triangulation Must-know ​

In plain words: write down the behaviours you want, pick one, write a test that fails, write the least code that makes it pass, tidy the code with the tests as a safety net, pick the next.

Common misunderstanding: "TDD is writing every test before any code" and "TDD is red-green only". Beck's "Canon TDD" calls both strawmen: the list is of scenarios, only one becomes a test at a time, and refactoring is the step people skip. Fowler agrees: "The most common way that I hear to screw up TDD is neglecting the third step."

Definition (Canon TDD, 11 December 2023):

1. Test listbehaviour cases,no design yet2. Redone real test, run it,see it fail for the right reason3. Greensimplest change that makesthis and all earlier tests pass4. Refactoroptional; behaviour fixed,tests stay greentick off, pick nextrepeat until the list is empty
StepWhat you doNamed mistakes in Canon TDD
1. Test listList the behaviour variants, including how existing behaviour must not breakMixing in implementation design decisions
2. Write one testOne automated test with set-up, invocation and assertions; interface decisions happen hereNo assertions "just to get code coverage"; converting the whole list into tests at once
3. Make it passChange the system so this and all earlier tests passDeleting assertions; pasting computed values into expected values; mixing in refactoring
4. Refactor (optional)Make implementation design decisions without changing behaviourRefactoring further than necessary for this session; abstracting too soon ("Duplication is a hint, not a command.")
5. RepeatUntil the list is empty: "until your fear for the behavior of the code has been transmuted into boredom"

Beck's overview says the goal is a state where "everything that used to work still works", "the new behavior works as expected", the system is "ready for the next change" and the programmer and colleagues feel confident. Fowler adds the two benefits of test-first: it produces self-testing code, and "thinking about the test first forces us to think about the interface to the code first".

Vocabulary the keyword list asks for:

TermMeaningSource status
Test-firstWrite the test before the code it exercisesFowler: XPE2 calls it Test-First Programming
Red-green-refactorThe three steps repeated; red means the new test fails, green that it passesFowler TDD page, Wikipedia (secondary)
TriangulationA common TDD technique: add a second example with a different value so the simple constant answer stops working and you must generaliseNo saved source; described in own words, not attributed
Fake itReturn a constant to get to green, then generaliseNo saved source; described in own words
Transformation priority premisePrefer the simplest code transformation that passes the next test; transformations run from specific to genericRobert C. Martin, 27 May 2013 (read)

Martin's premise lists transformations in rough order of complexity: ({}->nil), (nil->constant), (constant->constant+), (constant->scalar), (statement->statements), (unconditional->if), (scalar->array), (array->container), (statement->recursion), (if->while), (expression->function), (variable->assignment). His mantra: "As the tests get more specific, the code gets more generic." He says it is a premise, not a law.

Timeline of a real cycle (the String Calculator kata, steps 1 to 6 of Roy Osherove's kata page; the final code is in the module's tdd package):

text
     Step  Test added to the list                RED (what fails)                  GREEN (smallest change)            REFACTOR
1    ""            -> 0                          Add undefined                     return 0                           none
2    "1"           -> 1                          got 0, want 1                     (constant->scalar): parse the string  none
3    "7"           -> 7  (triangulate)           passes already                    nothing: keeps the generalisation  none
4    "1,2"         -> 3                          Atoi fails on "1,2"               (unconditional->if) split on comma extract constants
5    "1,2,3,4"     -> 10                         passes with the loop              (if->while) loop over fields       none
6    "1\n2,3"      -> 6                          Atoi fails on "1\n2"              replace newline by comma           name the separators
7    "//;\n1;2"    -> 3                          Atoi fails on "//;\n1;2"          cut the header, new delimiter      extract header parsing
8    "1,-2"        -> error "negatives not allowed: -2"   returns sum              collect negatives, return error    none
9    "2,1001"      -> 2                          got 1003                          skip numbers above 1000            named constant maxOperand

Row 3 shows a useful property: a triangulating test that passes at once is still worth keeping, because it proves the generalisation. If it had failed, the earlier code would have been a hard-coded constant.

Real scenarios: a pricing engine grown rule by rule; a parser; a bug fix (write the failing regression test first, then fix); legacy code (characterisation tests first, then change). TDD is a poor fit for exploratory UI work and spikes where you do not yet know the interface; Beck says plainly "if you're doing something different than the following workflow & it works for you, congratulations".

Go: the final state, with the table of test cases as the test list:

go
// Package tdd is the final state of a string-calculator kata that was driven
// test-first (Roy Osherove's String Calculator kata, steps 1 to 6; the steps are shown on the page).
package tdd

import (
	"fmt"
	"strconv"
	"strings"
)

// maxOperand is the largest number that still counts; bigger ones are ignored.
const maxOperand = 1000

// Add sums the numbers in s. Numbers are separated by commas or newlines. A
// first line of the form "//<delimiter>\n" replaces both separators with a
// custom delimiter. Negative numbers are an error that lists all of them.
// Numbers above 1000 are ignored. The empty string sums to zero.
func Add(s string) (int, error) {
	if s == "" {
		return 0, nil
	}
	seps := []string{",", "\n"}
	if rest, ok := strings.CutPrefix(s, "//"); ok {
		delim, body, found := strings.Cut(rest, "\n")
		if !found || delim == "" {
			return 0, fmt.Errorf("malformed custom delimiter header in %q", s)
		}
		seps, s = []string{delim}, body
	}
	for _, sep := range seps[1:] {
		s = strings.ReplaceAll(s, sep, seps[0])
	}

	sum := 0
	var negatives []string
	for _, field := range strings.Split(s, seps[0]) {
		n, err := strconv.Atoi(strings.TrimSpace(field))
		if err != nil {
			return 0, fmt.Errorf("not a number: %q", field)
		}
		if n < 0 {
			negatives = append(negatives, field)
			continue
		}
		if n <= maxOperand {
			sum += n
		}
	}
	if len(negatives) > 0 {
		return 0, fmt.Errorf("negatives not allowed: %s", strings.Join(negatives, ","))
	}
	return sum, nil
}
go
package tdd

import "testing"

// The table is the test list from step 1 of Canon TDD, in the order the
// tests were turned into code: each row forced one small change.
func TestAdd(t *testing.T) {
	tests := []struct {
		name    string
		in      string
		want    int
		wantErr string // empty means no error expected
	}{
		{name: "empty is zero", in: "", want: 0},
		{name: "one number is itself", in: "1", want: 1},
		{name: "triangulate: another single number", in: "7", want: 7},
		{name: "two numbers", in: "1,2", want: 3},
		{name: "many numbers", in: "1,2,3,4", want: 10},
		{name: "newline is a separator", in: "1\n2,3", want: 6},
		{name: "custom delimiter", in: "//;\n1;2", want: 3},
		{name: "numbers above 1000 are ignored", in: "2,1001", want: 2},
		{name: "1000 itself counts", in: "2,1000", want: 1002},
		{name: "negative is rejected", in: "1,-2", wantErr: "negatives not allowed: -2"},
		{name: "all negatives are listed", in: "-1,2,-3", wantErr: "negatives not allowed: -1,-3"},
		{name: "garbage is rejected", in: "1,x", wantErr: `not a number: "x"`},
		{name: "header without newline", in: "//;", wantErr: `malformed custom delimiter header in "//;"`},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, err := Add(tt.in)
			switch {
			case tt.wantErr != "" && (err == nil || err.Error() != tt.wantErr):
				t.Fatalf("Add(%q) error = %v, want %q", tt.in, err, tt.wantErr)
			case tt.wantErr == "" && err != nil:
				t.Fatalf("Add(%q) unexpected error: %v", tt.in, err)
			case got != tt.want:
				t.Errorf("Add(%q) = %d, want %d", tt.in, got, tt.want)
			}
		})
	}
}

A failing run looks like this. It is real output from a scratch copy of the package with the maxOperand check disabled, which is exactly the state after row 9's test is added and before its fix:

text
--- FAIL: TestAdd (0.00s)
    --- FAIL: TestAdd/numbers_above_1000_are_ignored (0.00s)
        strcalc_test.go:37: Add("2,1001") = 1003, want 2
FAIL
FAIL	academy/testing-strategy-tdd/tdd	0.398s
FAIL

PHP: the same kata as a PHPUnit data provider (#[DataProvider] attribute in PHPUnit 12) and the class under test:

php
<?php

declare(strict_types=1);

namespace App\Kata;

use InvalidArgumentException;

final class StringCalculator
{
    private const MAX_OPERAND = 1000;

    public function add(string $input): int
    {
        if ($input === '') {
            return 0;
        }

        $separators = [',', "\n"];
        if (str_starts_with($input, '//')) {
            [$delimiter, $input] = explode("\n", substr($input, 2), 2) + [1 => null];
            if ($delimiter === '' || $input === null) {
                throw new InvalidArgumentException('malformed custom delimiter header');
            }
            $separators = [$delimiter];
        }

        $fields = explode($separators[0], str_replace($separators, $separators[0], $input));
        $sum = 0;
        $negatives = [];
        foreach ($fields as $field) {
            if (!is_numeric($field)) {
                throw new InvalidArgumentException("not a number: {$field}");
            }
            $n = (int) $field;
            if ($n < 0) {
                $negatives[] = $n;
            } elseif ($n <= self::MAX_OPERAND) {
                $sum += $n;
            }
        }
        if ($negatives !== []) {
            throw new InvalidArgumentException('negatives not allowed: ' . implode(',', $negatives));
        }

        return $sum;
    }
}
php
<?php

declare(strict_types=1);

namespace Tests\Unit;

use App\Kata\StringCalculator;
use InvalidArgumentException;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;

final class StringCalculatorTest extends TestCase
{
    /** @return iterable<string, array{string, int}> */
    public static function sums(): iterable
    {
        yield 'empty is zero' => ['', 0];
        yield 'one number is itself' => ['1', 1];
        yield 'triangulate: another single number' => ['7', 7];
        yield 'two numbers' => ['1,2', 3];
        yield 'newline is a separator' => ["1\n2,3", 6];
        yield 'custom delimiter' => ["//;\n1;2", 3];
        yield 'above 1000 is ignored' => ['2,1001', 2];
    }

    #[DataProvider('sums')]
    public function test_add(string $input, int $expected): void
    {
        $this->assertSame($expected, (new StringCalculator())->add($input));
    }

    public function test_all_negatives_are_listed(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('negatives not allowed: -1,-3');

        (new StringCalculator())->add('-1,2,-3');
    }
}

The PHP add was exercised with a plain script for the eight inputs of the list (all matched); PHPUnit itself was not run here.

Anatomy of a good test: arrange act assert, naming, one assertion per concept, FIRST, table-driven tests Must-know ​

In plain words: a good test reads like a tiny story: set the scene, do one thing, check one outcome, and when it fails the name and the message tell you what broke.

Common misunderstanding: "One assertion per test" means literally one assert call. The useful rule is one assertion per concept: several assertions are fine when they all describe one behaviour (the status code and the body of one response); two unrelated behaviours belong in two tests.

Definition:

ElementRuleWhyExample
Arrange act assert (also written given, when, then)Three visible phases, in that order, one actA reader finds the point of the test at once; Vocke notes both forms describe the same structureBuild order, call Shipping, compare
Test namingThe name states the situation and the expected behaviour, not the methodA failing name should be a bug reportgold at the threshold ships free
One assertion per conceptGroup assertions that describe one outcomeFailures point to one causeStatus and body of one response
Useful failure messagePrint the input, the got value and the want valueThe Google Go style guide: "It should be possible to diagnose a test's failure without reading the test's source."Add("2,1001") = 1003, want 2
Table-driven testsOne test function, a slice of named cases, one loop with t.RunNew case = one new row; each case reports separatelyTestAdd, TestShipping in the module
FIRSTFast, Isolated, Repeatable, Self-validating, TimelyOttinger and Langr's checklist for unit testsSee table below
No logic in testsNo loops, conditionals or computed expectations that mirror production codeA test with logic needs its own testHard-code the expected value
Test behaviour, not implementationAssert on what callers can observeRefactoring must not break testsCheck the saved order, not the private helper called

FIRST, from the saved Ottinger post (the post calls the second letter "Isolated"; many lists say "Independent"):

LetterMeaning in the post
Fast"If you hesitate to run the tests after a simple one-liner change, your tests are far too slow."
IsolatedTests isolate failures; they "must not have any order-of-run dependency" and pass or fail the same in a suite or alone
RepeatableRun repeatedly without intervention; no dependence on assumed initial state or on external services that might not be available
Self-validatingPass or fail, no human interpretation
TimelyWritten "immediately before the code that makes the tests pass"

Timeline of a test that fails usefully (a pricing rule changes):

text
     Step  Who        What happens
1    Mon   CI         FAIL TestShipping/gold_just_below_the_threshold_pays
2    Mon   Dev        reads: Shipping() = 0, want 700 (subtotal 4000)  -- cause and context in one line
3    Mon   Dev        the threshold constant moved from 5000 to 4000 in a refactor; fixes it in two minutes
4    Tue   Dev B       a test named TestShipping2 fails with "expected true": 40 minutes to understand

Real scenarios: a table of tax rules with a row per country; a regression row per incident; a name such as TestOrder_CancelAfterShipment_ReturnsError that survives as documentation.

Go: Go's culture is table tests with subtests (t.Run, Go 1.7) and %q in messages; the Google Go style guide has a section called "Useful test failures" (cause, inputs, actual result, expectation). The module's builders.TestShipping and tdd.TestAdd are the model; see Testing & Benchmarking for the mechanics and the Go blog's subtests post. Go 1.24 added testing.T.Context and testing.B.Loop to the toolbox.

PHP: PHPUnit's #[DataProvider] attribute (shown in StringCalculatorTest) and Pest's ->with([...]) datasets (shown in CheckoutTest.pest.php) are the table-test equivalents; Laravel names tests test_something_happens in PHPUnit style or it('does something') in Pest style.

Test data: builders, object mothers, factories, fixtures Important ​

In plain words: a test needs objects in a certain state. A builder, a factory or a fixture creates them so that each test states only the one detail it cares about.

Common misunderstanding: "Shared fixtures keep tests DRY." A fixture shared across tests makes every test depend on data it did not set up, so changing one row breaks unrelated tests. Prefer data created per test, with defaults hidden in a builder or factory.

Definition:

TechniqueWhat it isStrengthWeaknessWhere
Fixture (xUnit sense)The state a test needs before it runs; set up in setUp/TestMain/fileSimple for static reference dataHidden coupling, "mystery guest"PHPUnit fixtures, Go testdata/
Object motherA function returning a named, ready-made example (standardCustomer())Short tests, shared vocabularyGrows a variant per scenario; tests differ by hidden fieldsFowler's ObjectMother entry
Test data builderStarts from a valid default, With methods change one thing (Nat Pryce's pattern)Tests show only relevant details; defaults change in one placeBoilerplate in languages without named argumentsOrderBuilder in Go
Factory (Laravel)A class with definition() and named state() methods; make() or create()Realistic random data, relationships (->for(), ->has()), sequences, callbacksRandom data can hide order dependence; seed it if a failure must replayDatabase\Factories\OrderFactory
SeederLoads reference data into the databaseNeeded lookup tables (countries, roles)Slow if every test seeds everythingLaravel db:seed and the Seed attribute

Timeline of a builder paying off (a new mandatory field is added to Customer):

text
     Step  Without a builder                         With a builder
1    add Customer.Region (required)                  add Customer.Region (required)
2    97 tests construct Customer{...} literally      1 default in anOrder() gets Region: "EU"
3    97 compile errors or wrong zero values          0 tests change
4    afternoon of mechanical edits, a few mistakes   run the suite

Real scenarios: an order with a gold customer and two lines; a user with an expired subscription (a named factory state); a hundred rows for a pagination test (->count(100)); fixtures kept in a testdata directory for a parser.

Go: OrderBuilder shows the pattern with a fluent chain; functional options or plain struct literals with a default() helper work equally well. The object mother is standardCustomer().

go
// Package builders shows test data builders and an object mother around a
// small shipping rule.
package builders

// Customer is who orders.
type Customer struct {
	Name string
	Tier string // "standard" or "gold"
}

// Line is one product line of an order. Money is integer cents.
type Line struct {
	SKU       string
	Qty       int
	UnitCents int64
}

// Order is a basket plus delivery choice.
type Order struct {
	ID       string
	Customer Customer
	Lines    []Line
	Express  bool
}

// Subtotal sums the lines.
func (o Order) Subtotal() int64 {
	var sum int64
	for _, l := range o.Lines {
		sum += int64(l.Qty) * l.UnitCents
	}
	return sum
}

const (
	freeShippingFrom = 5000
	standardShipping = 700
	expressShipping  = 1500
)

// Shipping is free from 50.00 for gold customers on standard delivery,
// 7.00 otherwise on standard delivery, and always 15.00 for express.
func Shipping(o Order) int64 {
	switch {
	case o.Express:
		return expressShipping
	case o.Customer.Tier == "gold" && o.Subtotal() >= freeShippingFrom:
		return 0
	default:
		return standardShipping
	}
}
go
package builders

import "testing"

// OrderBuilder is a test data builder: it starts from a valid default and each
// With method changes one thing, so a test mentions only what it is about.
type OrderBuilder struct{ o Order }

func anOrder() *OrderBuilder {
	return &OrderBuilder{o: Order{
		ID:       "o-default",
		Customer: Customer{Name: "Ada", Tier: "standard"},
		Lines:    []Line{{SKU: "pen", Qty: 1, UnitCents: 1000}},
	}}
}

func (b *OrderBuilder) Gold() *OrderBuilder    { b.o.Customer.Tier = "gold"; return b }
func (b *OrderBuilder) Express() *OrderBuilder { b.o.Express = true; return b }
func (b *OrderBuilder) WithLine(sku string, qty int, unit int64) *OrderBuilder {
	b.o.Lines = append(b.o.Lines, Line{SKU: sku, Qty: qty, UnitCents: unit})
	return b
}
func (b *OrderBuilder) Build() Order { return b.o }

// standardCustomer is an object mother: one named, ready-made example.
func standardCustomer() Customer { return Customer{Name: "Ada", Tier: "standard"} }

func TestShipping(t *testing.T) {
	tests := []struct {
		name  string
		order Order
		want  int64
	}{
		{"standard customer pays standard shipping", anOrder().Build(), 700},
		{"gold below the threshold still pays", anOrder().Gold().Build(), 700},
		{"gold at the threshold ships free", anOrder().Gold().WithLine("book", 1, 4000).Build(), 0},
		{"gold just below the threshold pays", anOrder().Gold().WithLine("book", 1, 3999).Build(), 700},
		{"express is never free", anOrder().Gold().Express().WithLine("book", 1, 9000).Build(), 1500},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := Shipping(tt.order); got != tt.want {
				t.Errorf("Shipping() = %d, want %d (subtotal %d)", got, tt.want, tt.order.Subtotal())
			}
		})
	}
}

func TestObjectMother(t *testing.T) {
	o := Order{ID: "o-1", Customer: standardCustomer(), Lines: []Line{{SKU: "pen", Qty: 2, UnitCents: 250}}}
	if got := o.Subtotal(); got != 500 {
		t.Errorf("Subtotal() = %d, want 500", got)
	}
}

Laravel: a factory is Laravel's builder. The saved Laravel 13 page shows definition(), state(), relationships (for, has), sequences and afterCreating callbacks:

php
<?php

declare(strict_types=1);

namespace Database\Factories;

use App\Models\Order;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * A Laravel model factory: valid by default, one named state per business
 * situation. It is the Eloquent counterpart of a test data builder.
 *
 * @extends Factory<Order>
 */
final class OrderFactory extends Factory
{
    protected $model = Order::class;

    /** @return array<string, mixed> */
    public function definition(): array
    {
        return [
            'user_id' => User::factory(),
            'status' => 'pending',
            'total_cents' => fake()->numberBetween(500, 20000),
            'express' => false,
        ];
    }

    public function paid(): static
    {
        return $this->state(fn (array $attributes) => ['status' => 'paid']);
    }

    public function express(): static
    {
        return $this->state(fn (array $attributes) => ['express' => true]);
    }

    public function worth(int $cents): static
    {
        return $this->state(fn (array $attributes) => ['total_cents' => $cents]);
    }
}

Tests read Order::factory()->for($user)->worth(2500)->create() (see Database tests). Factories need a model that use HasFactory; that model is in the lab (lint only).

Database tests: RefreshDatabase, DatabaseTransactions, testcontainers, in-memory fakes versus real dependencies Must-know ​

In plain words: most bugs in business apps live in the SQL, the mappings and the transaction boundaries. A test that never touches a real database cannot find them, so run some tests against the real engine and make each one clean up after itself.

Common misunderstanding: "An in-memory SQLite database is as good as PostgreSQL for tests." It is fast and convenient, but types, constraints, locking, JSON functions and SQL dialects differ, so a green SQLite test can hide a PostgreSQL failure. Use SQLite for speed where the schema allows it, and run the critical repository tests against the production engine.

Definition: four ways to isolate tests that share a database.

StrategyHowCostCaveat
Transaction per test, rolled backBEGIN before, ROLLBACK afterCheapest; no clean-up SQLCode under test that opens another connection, or that commits, escapes it
Truncate or delete after each testClean tables explicitlyMedium; needs order for foreign keysForgotten tables leak state
Migrate or recreate per testRebuild the schemaSlowLaravel notes DatabaseMigrations and DatabaseTruncation are "significantly slower" than RefreshDatabase
Database per test processOne schema or container per workerFast in parallel, more set-upLaravel creates one test database per parallel process with a process-token suffix

What the engines do:

ProductBehaviour that matters in tests
PostgreSQLTransactional DDL: the PostgreSQL wiki says it can perform transactional DDL "via its Write-Ahead Log design", backing out even table creation. Serialization failures use SQLSTATE 40001 (serialization_failure, class 40 Transaction Rollback in the error-code appendix)
MySQL, InnoDBThe MySQL manual's implicit-commit page: some statements (data definition statements among them) end the current transaction "as if you had done a COMMIT before executing the statement", so transaction-per-test does not roll back schema changes
SQLiteIn-memory databases: opening two connections with the filename :memory: "will create two independent in-memory databases"; fine for many Laravel feature tests, but types and locking differ from PostgreSQL
CockroachDBTransaction retry errors "use the SQLSTATE error code 40001"; transaction-per-test on a single node hides the retries you will see under contention

The rows quote the saved pages (PostgreSQL error-code appendix and wiki, MySQL 8.4 manual, SQLite in-memory page, CockroachDB retry reference). Engines not listed (SQL Server, Oracle, MongoDB, Redis) were not sourced for this chapter; check their manuals. The transaction and isolation chapters hold the detail (ACID & Transactions).

The SQL a transaction-per-test run executes:

sql
BEGIN;                                                       -- RefreshDatabase / WithTx starts here
INSERT INTO orders (id, user_id, status, total_cents)
VALUES (1, 7, 'pending', 2500);                              -- the test arranges its data
UPDATE orders SET status = 'paid' WHERE id = 1;              -- the code under test acts
SELECT status FROM orders WHERE id = 1;                      -- the test asserts: paid
ROLLBACK;                                                    -- nothing was ever committed

Timeline of two tests sharing a database (why the rollback matters):

text
     Step  Test A (creates user "ada")                 Test B (expects an empty users table)
1    BEGIN
2    INSERT users('ada')
3                                                       BEGIN (own connection, own snapshot)
4                                                       SELECT count(*) FROM users  -- 0, A is uncommitted
5    ROLLBACK
6                                                       passes, whatever the order
     Without transactions: B sees 'ada' if A ran first; green alone, red in the suite, order-dependent

Real scenarios: repository tests against PostgreSQL in a container; Laravel feature tests with RefreshDatabase; migration tests that run the full migration chain once per CI run; an in-memory fake for unit tests with a contract test against the real repository.

Go: the dbtest.WithTx helper begins a transaction and registers a t.Cleanup rollback (t.Cleanup arrived in Go 1.14). Execer is satisfied by *sql.DB and *sql.Tx, so production code runs unchanged inside the test transaction. The example uses a tiny recording driver so it runs without a server; a real project swaps in pgx.

go
// Package dbtest shows the transaction-rollback-per-test pattern with
// database/sql. It is the Go counterpart of Laravel's RefreshDatabase.
package dbtest

import (
	"database/sql"
	"testing"
)

// WithTx begins a transaction, hands it to fn and ALWAYS rolls it back when
// the test ends. Nothing a test writes is ever committed, so tests cannot
// leak rows into each other and need no cleanup SQL.
//
// Limits: code under test that opens its own connection, or that itself
// commits or uses nested transactions incorrectly, will not see or respect
// this transaction. Pass the *sql.Tx (through an interface) into the code.
func WithTx(t testing.TB, db *sql.DB, fn func(tx *sql.Tx)) {
	t.Helper()
	tx, err := db.Begin()
	if err != nil {
		t.Fatalf("begin: %v", err)
	}
	t.Cleanup(func() {
		if err := tx.Rollback(); err != nil && err != sql.ErrTxDone {
			t.Errorf("rollback: %v", err)
		}
	})
	fn(tx)
}

// AddUser is the code under test: it inserts one row using the given Execer.
func AddUser(ex Execer, name string) error {
	_, err := ex.Exec("INSERT INTO users (name) VALUES ($1)", name)
	return err
}

// Execer is satisfied by *sql.DB and *sql.Tx, so production code can run
// inside a request transaction or a test transaction without knowing which.
type Execer interface {
	Exec(query string, args ...any) (sql.Result, error)
}
go
package dbtest

import (
	"database/sql"
	"reflect"
	"testing"
)

func TestWithTx_RollsBackWhatTheTestWrote(t *testing.T) {
	db, rec := newFakeDB("fake-rollback")
	defer db.Close()

	// The inner subtest finishes first, which runs its Cleanup (the rollback)
	// before the outer test inspects the recorder.
	t.Run("write inside the test transaction", func(t *testing.T) {
		WithTx(t, db, func(tx *sql.Tx) {
			if err := AddUser(tx, "ada"); err != nil {
				t.Fatal(err)
			}
		})
	})

	want := []string{"BEGIN", "EXEC INSERT INTO users (name) VALUES ($1)", "ROLLBACK"}
	if got := rec.snapshot(); !reflect.DeepEqual(got, want) {
		t.Errorf("events = %v, want %v", got, want)
	}
	for _, e := range rec.snapshot() {
		if e == "COMMIT" {
			t.Error("a test transaction must never commit")
		}
	}
}

func TestAddUser_WorksOnAPlainDB(t *testing.T) {
	db, rec := newFakeDB("fake-plain")
	defer db.Close()
	if err := AddUser(db, "grace"); err != nil {
		t.Fatal(err)
	}
	if got := rec.snapshot(); len(got) != 1 {
		t.Errorf("events = %v, want a single EXEC", got)
	}
}

Testcontainers (described, not run here, no Docker): Testcontainers for Go starts real dependencies in Docker for the duration of a test. The saved getting-started guide uses the postgres module (github.com/testcontainers/testcontainers-go/modules/postgres), postgres.WithInitScripts(...) for the schema, a wait strategy for readiness, and pgContainer.Terminate(ctx) inside t.Cleanup. That guide targets an older module version (v0.20.1, with postgres.RunContainer); check the current module docs before copying it. Testcontainers also has an official PHP library (testcontainers/testcontainers-php, PHP 8.1 or newer). In CI the machine needs a Docker-compatible runtime. Pattern: one container per package in TestMain (fast), transaction per test inside it (clean).

Laravel: Illuminate\Foundation\Testing\RefreshDatabase runs each test inside a transaction and, per the 13.x docs, "does not migrate your database if your schema is up to date"; DatabaseTransactions (a trait in the same namespace, whose beginDatabaseTransaction starts a transaction on each connection in connectionsToTransact()) only wraps each test in a transaction and never migrates, so the schema must already exist. Parallel runs get one database per process automatically.

php
<?php

declare(strict_types=1);

namespace Tests\Feature;

use App\Models\Order;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;

/**
 * A Feature test: boots the application, goes through routing, middleware,
 * validation and the database. RefreshDatabase wraps each test in a
 * transaction that is rolled back, so tests never see each other's rows.
 */
final class CheckoutFeatureTest extends TestCase
{
    use RefreshDatabase;

    public function test_paying_an_order_charges_the_gateway_and_marks_it_paid(): void
    {
        Http::fake(['payments.example/*' => Http::response(['receipt' => 'r-1'], 200)]);
        $user = User::factory()->create();
        $order = Order::factory()->for($user)->worth(2500)->create();

        $response = $this->actingAs($user)->postJson("/api/orders/{$order->id}/pay");

        $response->assertOk()->assertJsonPath('receipt', 'r-1');
        $this->assertDatabaseHas('orders', ['id' => $order->id, 'status' => 'paid']);
        Http::assertSentCount(1);
    }

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

        $this->actingAs(User::factory()->create())
            ->postJson("/api/orders/{$order->id}/pay")
            ->assertForbidden();

        $this->assertDatabaseHas('orders', ['id' => $order->id, 'status' => 'pending']);
    }
}

Flaky tests: non-determinism, hermetic tests, quarantine, retries Must-know ​

In plain words: a flaky test passes and fails on the same code. It is a broken instrument: once people learn to rerun red builds, real failures hide among the false ones.

Common misunderstanding: "Add an automatic retry and move on." Google's own mitigation (a flag that makes a test report failure only after three failures in a row) "encourages developers to ignore flakiness in their own tests"; the same post imagines a 15-minute integration test marked flaky, where a real break is discovered only after three executions, 45 minutes later. Retries measure flakiness; they must not hide it.

Definition: Google defines a flaky result as "a test that exhibits both a passing and a failing result with the same code". Fowler's article names the causes and the cure.

Cause (Fowler)What happensRemedyExample in this module
Lack of isolationTests share state and pass only in one orderOwn data per test; random order in CI; transaction per testt.TempDir, t.Parallel, go test -shuffle=on
Asynchronous behaviourThe test checks before the work finishedPoll for the outcome, never sleep a guessed timehermetic.Eventually
Remote servicesNetwork, third party, shared stagingTest doubles plus contract testsContract tests
TimeReal clock, time zones, day boundaries, TTLsInject a clockhermetic.FakeClock, TTLCache
Resource leaksOpen connections, goroutines, temp files accumulateClose in t.Cleanup; leak checkst.Cleanup(func() { ... })
Also commonMap iteration order, random data, concurrency racesSort for output; seed random data; go test -racehermetic.Summary sorts keys

Numbers from Google (2016): about 1.5 % of all test runs report a flaky result; about 84 % of pass-to-fail transitions seen in post-submit testing involved a flaky test; with 1000 tests per project and 1.5 % flaky results, about 15 tests fail per run and need investigation. The post also describes a tool that "automatically quarantines" a test whose flakiness is too high, with the warning that this "could easily mask a real race condition".

Quarantine (Fowler): "Place any non-deterministic test in a quarantined area. (But fix quarantined tests quickly.)" Keep the quarantine from becoming a graveyard with a numeric limit ("only allow 8 tests in quarantine") or a time limit ("no longer than a week"). Fowler's stronger advice: "you really ought to throw a non-deterministic test away, since if you don't it has an infectious quality."

Timeline of a flaky test's life:

text
     Step  Who        What happens
1    Mon   CI         TestExpiry fails on main; rerun passes
2    Mon   Team       "flaky, ignore"; two more reruns this week
3    Wed   Dev        a real expiry bug lands; TestExpiry fails; the team reruns again
4    Thu   Customer   sessions expire a minute early in production
5    Fri   Team       post-mortem: the test slept 1.1 s for a 1 s TTL; the clock is injected now

Real scenarios: a test that compares two timestamps taken a millisecond apart; a test that depends on map order; a test that waits Sleep(2s) for a queue consumer; a test that shares one /tmp/out.json; a UI test that clicks before the element exists.

Go: make time an argument, sort map output, poll with a deadline, and use the toolchain: go test -race finds data races, -shuffle=on (Go 1.17) randomises test order and prints the seed so a failure can be replayed, -count=N repeats, and t.Parallel() forces independence (a test that uses t.Setenv cannot be parallel: "testing: test using t.Setenv, t.Chdir, or cryptotest.SetGlobalRandom can not use t.Parallel"). Go 1.25 adds testing/synctest: "time package functions operate on a fake clock and the clock moves forward instantaneously if all goroutines in the bubble are blocked", which removes sleeps from concurrent tests. The module's hermetic package:

go
// Package hermetic shows how to remove the usual sources of non-determinism
// from a test: the clock, sleeping, map order and shared state.
package hermetic

import (
	"fmt"
	"sort"
	"sync"
	"testing"
	"time"
)

// Clock is the only way code under test may ask for the time.
type Clock interface{ Now() time.Time }

// SystemClock is the production clock.
type SystemClock struct{}

// Now returns the wall-clock time.
func (SystemClock) Now() time.Time { return time.Now() }

// FakeClock is a clock tests move by hand.
type FakeClock struct {
	mu  sync.Mutex
	now time.Time
}

// NewFakeClock starts a FakeClock at t.
func NewFakeClock(t time.Time) *FakeClock { return &FakeClock{now: t} }

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

// Advance moves the fake time forward.
func (c *FakeClock) Advance(d time.Duration) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.now = c.now.Add(d)
}

// TTLCache keeps values for a fixed time to live, measured on its Clock.
type TTLCache struct {
	clock Clock
	ttl   time.Duration
	mu    sync.Mutex
	items map[string]entry
}

type entry struct {
	value   string
	expires time.Time
}

// NewTTLCache returns an empty cache.
func NewTTLCache(c Clock, ttl time.Duration) *TTLCache {
	return &TTLCache{clock: c, ttl: ttl, items: map[string]entry{}}
}

// Set stores a value.
func (c *TTLCache) Set(key, value string) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.items[key] = entry{value: value, expires: c.clock.Now().Add(c.ttl)}
}

// Get returns a value that has not expired yet.
func (c *TTLCache) Get(key string) (string, bool) {
	c.mu.Lock()
	defer c.mu.Unlock()
	e, ok := c.items[key]
	if !ok || !c.clock.Now().Before(e.expires) {
		return "", false
	}
	return e.value, true
}

// Summary renders counts as sorted lines. Iterating a map directly would give
// a different order on every run, which is a classic flaky-test source.
func Summary(counts map[string]int) []string {
	keys := make([]string, 0, len(counts))
	for k := range counts {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	lines := make([]string, 0, len(keys))
	for _, k := range keys {
		lines = append(lines, fmt.Sprintf("%s=%d", k, counts[k]))
	}
	return lines
}

// Eventually polls cond until it is true or the timeout passes. It replaces a
// fixed time.Sleep: it is as fast as the system allows and fails with a clear
// message instead of racing.
func Eventually(t testing.TB, timeout, tick time.Duration, cond func() bool, msg string) {
	t.Helper()
	deadline := time.Now().Add(timeout)
	for {
		if cond() {
			return
		}
		if time.Now().After(deadline) {
			t.Fatalf("condition not met within %s: %s", timeout, msg)
		}
		time.Sleep(tick)
	}
}

// SkipInShort marks a test as "medium": it is skipped under go test -short.
func SkipInShort(t testing.TB) {
	t.Helper()
	if testing.Short() {
		t.Skip("skipping medium test in -short mode")
	}
}
go
package hermetic

import (
	"os"
	"path/filepath"
	"reflect"
	"sync/atomic"
	"testing"
	"time"
)

// No sleeping: the fake clock moves time, so the test takes microseconds and
// cannot be slowed down by a busy CI machine.
func TestTTLCache_ExpiresOnFakeClock(t *testing.T) {
	clock := NewFakeClock(time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC))
	cache := NewTTLCache(clock, time.Minute)
	cache.Set("k", "v")

	clock.Advance(59 * time.Second)
	if v, ok := cache.Get("k"); !ok || v != "v" {
		t.Fatalf("Get after 59s = (%q, %v), want (v, true)", v, ok)
	}
	clock.Advance(time.Second) // exactly the TTL: expired
	if _, ok := cache.Get("k"); ok {
		t.Fatal("value still present at exactly the TTL")
	}
}

func TestSummary_OrderIsDeterministic(t *testing.T) {
	counts := map[string]int{"b": 2, "a": 1, "c": 3}
	want := []string{"a=1", "b=2", "c=3"}
	// Repeat to make a map-order bug show up reliably instead of occasionally.
	for range 50 {
		if got := Summary(counts); !reflect.DeepEqual(got, want) {
			t.Fatalf("Summary() = %v, want %v", got, want)
		}
	}
}

// Asynchronous work: poll for the outcome instead of sleeping a guessed time.
func TestEventually_AsyncResult(t *testing.T) {
	var done atomic.Bool
	go func() {
		time.Sleep(5 * time.Millisecond)
		done.Store(true)
	}()
	Eventually(t, 2*time.Second, time.Millisecond, done.Load, "worker finished")
}

// Isolation: each parallel test gets its own directory and cleans up after
// itself, so tests can run in any order, together or alone.
func TestParallelTestsDoNotShareState(t *testing.T) {
	for _, name := range []string{"one", "two", "three"} {
		t.Run(name, func(t *testing.T) {
			t.Parallel()
			dir := t.TempDir() // removed automatically after the test
			path := filepath.Join(dir, "state.txt")
			if err := os.WriteFile(path, []byte(name), 0o600); err != nil {
				t.Fatal(err)
			}
			t.Cleanup(func() { _ = os.Remove(path) })
			got, err := os.ReadFile(path)
			if err != nil || string(got) != name {
				t.Errorf("read back %q (%v), want %q", got, err, name)
			}
		})
	}
}

func TestSkipInShort(t *testing.T) {
	SkipInShort(t) // runs in a normal run, skipped by go test -short
	if testing.Short() {
		t.Fatal("unreachable: SkipInShort should have skipped")
	}
}

PHP and Laravel: inject Illuminate\Support\Carbon time through Laravel's time-travel helpers (travel, travelTo, freezeTime on the test case; documented on the mocking page), seed fake() when order matters, and use Http::fake instead of a real HTTP call. PHPUnit reports risky tests, and Laravel's parallel runner needs a database per process (see CI and speed).

BDD, Gherkin, Cucumber, Behat, godog, specification by example, ATDD Important ​

In plain words: BDD is a way for business people and developers to agree on behaviour using concrete examples, and then to keep those examples as executable tests.

Common misunderstanding: "BDD is a tool: Cucumber." The Cucumber docs say it directly: "There's much more to BDD than just using Cucumber." The tool is the third step of three; the value is in the conversation that finds the examples.

Definition: Cucumber describes three practices: Discovery ("What it could do"), Formulation ("What it should do") and Automation ("What it actually does"). Examples are written in Gherkin: a Feature with Scenario blocks made of Given, When, Then, And, But steps, optionally Background, Scenario Outline and Rule. Wikipedia (secondary) says BDD "was originally derived from TDD practices". The sibling terms:

TermMeaningTool
BDDCollaborative practice around examples; automated checks followCucumber (many languages), Behat (PHP), godog (Go)
Given When ThenContext, action, outcome: the same shape as arrange, act, assertGherkin keywords
GherkinThe plain-language format for feature filesCucumber, Behat, godog
Specification by exampleUsing concrete examples as the specification (Fowler's entry)Any format; often Gherkin
ATDD (acceptance test-driven development)Write the acceptance test first, then the code; the outer loop around unit-level TDDOften the same tools as BDD
Behat"the PHP implementation of Cucumber"PHP
godog"the official Cucumber BDD framework for Golang"Go

Timeline of one example becoming a test:

text
     Step  Who                What happens
1    Mon   PO + dev + QA      three-amigos conversation about "free shipping": examples 4000 pays, 5000 free, express never free
2    Mon   Dev                writes the examples as a Gherkin scenario; PO reads and corrects the wording
3    Tue   Dev                step definitions call the real Shipping function; scenario red
4    Tue   Dev                implements the rule with unit-level TDD until the scenario is green
5    Fri   CI                 the scenario runs on every commit and documents the rule

A scenario for the module's shipping rule (a feature file, shown as text):

text
Feature: Shipping fee
  Scenario Outline: Gold customers ship free from 50.00 on standard delivery
    Given a gold customer with a basket worth <subtotal> cents
    And the delivery is <delivery>
    When the shipping fee is calculated
    Then the fee is <fee> cents

    Examples:
      | subtotal | delivery | fee  |
      | 4999     | standard | 700  |
      | 5000     | standard | 0    |
      | 9000     | express  | 1500 |

Real scenarios: payment and tax rules that business owners must confirm; regulatory behaviour that needs readable evidence; onboarding flows. BDD is a poor fit for pure technical code (a parser, a cache): there the table-driven unit test is the specification.

Go and PHP: godog binds Gherkin steps to Go functions and runs under go test; Behat does the same for PHP; in a Laravel project, Pest or PHPUnit feature tests with descriptive names are the lighter alternative. Neither godog nor Behat was installed or run here: expected, not run. The requirements side (stories, acceptance criteria) is on Requirements, PRDs & User Stories.

Contract tests and consumer-driven contracts: Pact Important ​

In plain words: when service A calls service B, a contract test checks that both sides agree on the messages without running both at once, so a change on one side that breaks the other is caught before deploy.

Common misunderstanding: "A contract test is a slow integration test." Pact's docs argue the opposite: "Do you set your house on fire to test your smoke alarm? No, you test the contract it holds with your ears by using the testing button." Each side is tested in isolation against a recorded contract.

Definition: a contract is a shared understanding between a consumer (a client that wants data) and a provider (the API that supplies it). Fowler's "Contract Test" entry describes the basic form: run your tests against the double, and periodically run contract tests that check "all the calls against your test doubles return the same results as a call to the external service would". The consumer-driven variant lets consumers state what they need and send the tests to the provider's team. In Pact:

Consumer CItest against a mock providerwrites the contract (pact)Pact Brokerstores contracts,verifications, versionsProvider CIreplays each interactionagainst the real providercan-i-deployis this version verifiedagainst what runs in prod?1. publish2. fetch pacts3. publish result
PieceRole
Consumer testRuns the real client against a Pact mock server; records the interactions as a pact (contract) file
Pact BrokerStores pacts, verification results and versions
Provider verificationReplays every interaction against the real provider and publishes the result
can-i-deployA broker check to "ensure that your contract tests have passed successfully before deploying a consumer or provider application"
MatrixThe grid of consumer and provider versions that have been tested against each other
Provider stateThe data set-up the provider needs for an interaction (Given a user with ID 10 exists)

Timeline of a breaking change caught by a contract:

text
     Step  Who             What happens
1    Mon   Consumer team   adds a test that reads "rate" as a number; pact published to the broker
2    Tue   Provider team   renames "rate" to "value" in a refactor
3    Tue   Provider CI     verification of the pact FAILS; can-i-deploy answers no
4    Tue   Both teams      talk: provider keeps "rate" and adds "value" (expand, then contract)
5    Wed   Provider CI     verification passes; deploy proceeds

Real scenarios: a checkout service that depends on a rates service; a mobile app and its API; two teams that cannot share a staging environment; message contracts for events on a queue (Pact supports messages as well as HTTP; see Testing Messaging for brokers).

Go (hand-rolled illustration, runs): the module's contract package shows the two halves without Pact: a JSON file written by the consumer team, a consumer test that replays it as a stand-in provider with httptest, and a provider test that replays it against the real handler and checks status, headers and field types (extra fields are allowed). The JSON file is not the Pact file format; real Pact adds matching rules, provider states and the broker. These tests are medium tests (localhost only) and skip under go test -short.

go
// Package contract is a hand-rolled, Pact-shaped consumer-driven contract
// test. The JSON file under pacts/ is NOT the Pact file format; it only shows
// the two steps: the consumer writes down what it needs, the provider proves
// it still delivers that. Real projects use Pact (pact-go) for the same steps
// plus matching rules and a broker; see the page.
package contract

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"strings"
)

// RatesClient is the consumer: it asks a rates service for an exchange rate.
type RatesClient struct {
	BaseURL string
	HTTP    *http.Client
}

// Rate returns the rate for a currency code, for example "EUR".
func (c RatesClient) Rate(ctx context.Context, currency string) (float64, error) {
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.BaseURL+"/rates/"+currency, nil)
	if err != nil {
		return 0, err
	}
	req.Header.Set("Accept", "application/json")
	resp, err := c.HTTP.Do(req)
	if err != nil {
		return 0, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return 0, fmt.Errorf("rates service: unexpected status %d", resp.StatusCode)
	}
	var body struct {
		Currency string  `json:"currency"`
		Rate     float64 `json:"rate"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
		return 0, fmt.Errorf("rates service: decode body: %w", err)
	}
	return body.Rate, nil
}

// RatesHandler is the provider side. It returns more fields than the consumer
// reads (updated_at), which a contract must allow.
func RatesHandler() http.Handler {
	rates := map[string]float64{"EUR": 0.92, "GBP": 0.79}
	mux := http.NewServeMux()
	mux.HandleFunc("GET /rates/{currency}", func(w http.ResponseWriter, r *http.Request) {
		code := strings.ToUpper(r.PathValue("currency"))
		rate, ok := rates[code]
		if !ok {
			http.Error(w, "unknown currency", http.StatusNotFound)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		_ = json.NewEncoder(w).Encode(map[string]any{
			"currency":   code,
			"rate":       rate,
			"updated_at": "2026-01-01T00:00:00Z",
		})
	})
	return mux
}
json
{
  "consumer": "checkout-service",
  "provider": "rates-service",
  "interactions": [
    {
      "description": "a request for the EUR rate",
      "providerState": "EUR has a rate",
      "request": {
        "method": "GET",
        "path": "/rates/EUR",
        "headers": { "Accept": "application/json" }
      },
      "response": {
        "status": 200,
        "headers": { "Content-Type": "application/json" },
        "body": { "currency": "EUR", "rate": 0.92 },
        "types": { "currency": "string", "rate": "number" }
      }
    },
    {
      "description": "a request for an unknown currency",
      "providerState": "XXX has no rate",
      "request": { "method": "GET", "path": "/rates/XXX" },
      "response": { "status": 404 }
    }
  ]
}
go
package contract

import (
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"os"
	"testing"

	"academy/testing-strategy-tdd/hermetic"
)

type pact struct {
	Consumer     string        `json:"consumer"`
	Provider     string        `json:"provider"`
	Interactions []interaction `json:"interactions"`
}

type interaction struct {
	Description   string `json:"description"`
	ProviderState string `json:"providerState"`
	Request       struct {
		Method  string            `json:"method"`
		Path    string            `json:"path"`
		Headers map[string]string `json:"headers"`
	} `json:"request"`
	Response struct {
		Status  int               `json:"status"`
		Headers map[string]string `json:"headers"`
		Body    map[string]any    `json:"body"`
		Types   map[string]string `json:"types"`
	} `json:"response"`
}

func loadPact(t *testing.T) pact {
	t.Helper()
	raw, err := os.ReadFile("pacts/checkout-service-rates-service.json")
	if err != nil {
		t.Fatal(err)
	}
	var p pact
	if err := json.Unmarshal(raw, &p); err != nil {
		t.Fatal(err)
	}
	return p
}

// Consumer side: a stand-in provider replays the recorded response, and the
// real client code runs against it. This is a medium test (localhost only).
func TestConsumer_WorksAgainstTheContract(t *testing.T) {
	hermetic.SkipInShort(t)
	p := loadPact(t)
	eur := p.Interactions[0]

	stand := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method != eur.Request.Method || r.URL.Path != eur.Request.Path {
			http.Error(w, "unexpected request", http.StatusTeapot)
			return
		}
		w.Header().Set("Content-Type", eur.Response.Headers["Content-Type"])
		_ = json.NewEncoder(w).Encode(eur.Response.Body)
	}))
	defer stand.Close()

	c := RatesClient{BaseURL: stand.URL, HTTP: stand.Client()}
	got, err := c.Rate(context.Background(), "EUR")
	if err != nil || got != 0.92 {
		t.Fatalf("Rate(EUR) = (%v, %v), want (0.92, nil)", got, err)
	}
}

// Provider side: replay every interaction against the REAL handler and check
// status, headers and the TYPES of the fields the consumer reads. Extra fields
// are allowed; a renamed or retyped field breaks this test.
func TestProvider_HonoursTheContract(t *testing.T) {
	hermetic.SkipInShort(t)
	p := loadPact(t)
	srv := httptest.NewServer(RatesHandler())
	defer srv.Close()

	for _, in := range p.Interactions {
		t.Run(in.Description, func(t *testing.T) {
			req, err := http.NewRequest(in.Request.Method, srv.URL+in.Request.Path, nil)
			if err != nil {
				t.Fatal(err)
			}
			for k, v := range in.Request.Headers {
				req.Header.Set(k, v)
			}
			resp, err := srv.Client().Do(req)
			if err != nil {
				t.Fatal(err)
			}
			defer resp.Body.Close()

			if resp.StatusCode != in.Response.Status {
				t.Fatalf("status = %d, want %d", resp.StatusCode, in.Response.Status)
			}
			for k, want := range in.Response.Headers {
				if got := resp.Header.Get(k); got != want {
					t.Errorf("header %s = %q, want %q", k, got, want)
				}
			}
			if len(in.Response.Types) == 0 {
				return
			}
			var body map[string]any
			if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
				t.Fatalf("decode body: %v", err)
			}
			for field, kind := range in.Response.Types {
				switch v := body[field].(type) {
				case string:
					if kind != "string" {
						t.Errorf("field %q is a string, contract says %s", field, kind)
					}
				case float64:
					if kind != "number" {
						t.Errorf("field %q is a number, contract says %s", field, kind)
					}
				default:
					t.Errorf("field %q missing or of type %T (%v), contract says %s", field, v, v, kind)
				}
			}
		})
	}
}

Real Pact in Go (expected, not run): the pact-go README (package github.com/pact-foundation/pact-go/v2/consumer) writes a consumer test in arrange, act, assert form with NewV2Pact(MockHTTPProviderConfig{Consumer: ..., Provider: ...}), AddInteraction().Given(...).UponReceiving(...).WithRequest(...).WillRespondWith(200), and mockProvider.ExecuteTest(t, func(config MockServerConfig) error { ... }); the provider side calls verifier.VerifyProvider(t, VerifyRequest{...}) with the pact file or a broker. Pact PHP (pact-foundation/pact-php) is the PHP counterpart.

Coverage: line versus branch coverage, and why targets mislead Must-know ​

In plain words: coverage tells you which code your tests did not run. It does not tell you the code was checked.

Common misunderstanding: "80 % coverage means 80 % of bugs are caught." A test with no assertions gives full coverage and zero protection; Fowler calls this assertion-free testing. His summary: "Test coverage is a useful tool for finding untested parts of a codebase. Test coverage is of little use as a numeric statement of how good your tests are."

Definition:

KindCountsTool
Statement or line coverageWhich lines or statements ranGo (go test -cover, modes set, count, atomic), PHPUnit (needs PCOV or Xdebug)
Branch coverageWhether each side of each decision ranPHPUnit with Xdebug (PCOV supports line coverage only); Go's tool reports statements
Path coverageWhich unique sequences of branches ranPHPUnit with Xdebug
Mutation scoreHow many injected faults the tests detectMutation testing

Go's -covermode flag takes set ("does this statement run?"), count ("how many times") or atomic (like count, correct in multithreaded tests); the default is set unless -race is enabled. PHPUnit's coverage page describes line, branch and path coverage and says that to report branch and path coverage the data must be collected with Xdebug, because "PCOV only supports line coverage".

Numbers to know: Fowler would expect "a coverage percentage in the upper 80s or 90s" from thoughtful testing and be "suspicious of anything like 100%". Google's guideline in its coverage best-practices post is 60 % "acceptable", 75 % "commendable", 90 % "exemplary", with the caveat that teams choose their own value, that "we should not be obsessing on how to get from 90% code coverage to 95%", and that human review of the uncovered lines matters more than the percentage. It also suggests per-commit goals for frequently changing code. Brian Marick, quoted by Fowler: "I expect a high level of coverage. Sometimes managers require one. There's a subtle difference."

Timeline of a coverage target going wrong:

text
     Step  Who        What happens
1    Jan   Manager    "no merge under 90 percent"
2    Feb   Team       tests without assertions appear: calling every function, checking nothing
3    Mar   CI         coverage 93 percent, green
4    Apr   Prod       a rounding bug in code that is "covered"; no test asserts the value
5    May   Team       replaces the gate with a rule: new code needs tests that fail when the code is wrong (see mutation testing)

Real scenarios: use coverage to find untested error paths; compare coverage of changed lines in a pull request; never use a global number as a performance metric.

Go: go test -cover ./..., -coverprofile=cover.out, then go tool cover -html=cover.out (the Go blog post "The cover story" explains how statements are instrumented).

PHP: run PHPUnit (or Pest) with a coverage driver loaded: PCOV is fast and line-only, Xdebug also reports branch and path coverage. --coverage-filter limits which source files count.

Mutation testing: Infection, go-mutesting, gremlins Important ​

In plain words: a tool makes a small deliberate bug in your code (a mutant) and runs the tests. If the tests still pass, they would not have caught that bug.

Common misunderstanding: "If coverage is high, tests are good." Gremlins' README: "Code coverage is unreliable as a measure of test quality. It is too easy to have tests that exercise a piece of code but don't test anything at all."

Definition: Infection's docs call mutation testing "a fault-based testing technique" with a "Mutation Score Indicator (MSI)": the percentage of mutants killed by the tests. It "mutates the source code with a set of predefined mutators" and for each mutant "runs the tests that cover changed line". Example from the Infection page: for return count($this->errors) > 0; the conditional boundary mutator produces >= 0 and the negation mutator < 0; a good test fails for both.

ToolLanguageStatus and cost
InfectionPHP (8.3+; PHPUnit, PhpSpec, Codeception)Needs Xdebug, phpdbg, PCOV or turbocov; --threads, minMsi/minCoveredMsi thresholds
Pest mutation testingPHPcovers() or mutates() in the test file; ./vendor/bin/pest --mutate, ideally with --parallel; needs Xdebug 3.0+ or PCOV
go-mutestingGogo-mutesting ./...; "find source code, which is not covered by any tests"
gremlinsGogremlins unleash; README says it works well on smallish modules and "a run can take hours" on very big ones; 0.x release, flags may change

Timeline of a surviving mutant:

text
     Step  What happens
1    mutation: `if qty > 0` becomes `if qty >= 0` in Shipping
2    run the tests that cover that line: all pass
3    mutant SURVIVED: no test checks qty == 0
4    add a table row qty = 0; the mutant is now killed (a test fails)

Real scenarios: run on the changed files of a pull request, not on the whole code base; use as a periodic audit of the most critical module (pricing, permissions); enforce a minimum MSI only for those modules.

Go and PHP: none of the mutation tools was installed here (the network fetch is out of scope for a build run): the commands are "expected, not run". They are slow, so keep them out of the fast gate.

Property-based testing and fuzzing: rapid, testing/quick, gopter, Eris Important ​

In plain words: instead of choosing examples, state a rule that must hold for every input ("the parts add up to the total") and let the library generate hundreds of inputs, then shrink a failure to a small one.

Common misunderstanding: "Property tests replace example tests." They find inputs you did not imagine; examples document intent. Use both.

Definition:

ToolLanguageNotes
testing/quickGo standard librarySimple generators; no shrinking; seed with quick.Config.Rand for reproducibility
pgregory.net/rapidGo"type-safe data generation using generics", "automatic minimization of failing test cases", state machine testing, no dependencies outside the standard library
gopterGoAnother property-testing library (not fetched here)
Native fuzzingGo 1.18 and laterfunc FuzzXxx(f *testing.F); seed corpus runs under plain go test; explore with go test -fuzz=FuzzXxx
ErisPHPProperty-based testing integrated with PHPUnit (giorgiosironi/eris)

Timeline of a property finding a bug:

text
     Step  What happens
1    property: sum(Split(total, n)) == total and max-min <= 1
2    generator tries total=100, n=3 -> passes ... 500 cases pass
3    a naive version used total/n for every part: sum is short by total mod n
4    the property fails for total=100, n=3; the shrinker reports the smallest case, e.g. total=1, n=2
5    the fix distributes the remainder; the property passes for all cases

Real scenarios: money splitting, serialisation round trips (decode(encode(x)) == x), sort and merge invariants, parsers that must never panic, idempotence (Normalize(Normalize(x)) == Normalize(x)), a state machine against a simple model.

Go: props.Split with quick.Check properties and a FuzzSplit target (the seed corpus runs as normal tests; the fuzzing engine was also run for 5 seconds in a scratch copy with go test ./props -run=NONE -fuzz=FuzzSplit -fuzztime=5s: about 4.9 million executions, no failure, result PASS):

go
// Package props has functions whose behaviour is best described by
// properties ("for every input ...") rather than single examples.
package props

import "errors"

// Split divides total cents into n parts that differ by at most one cent and
// add up to total exactly. Earlier parts receive the leftover cents.
func Split(total int64, n int) ([]int64, error) {
	if n <= 0 {
		return nil, errors.New("n must be positive")
	}
	if total < 0 {
		return nil, errors.New("total must not be negative")
	}
	base, rem := total/int64(n), total%int64(n)
	parts := make([]int64, n)
	for i := range parts {
		parts[i] = base
		if int64(i) < rem {
			parts[i]++
		}
	}
	return parts, nil
}

// Reverse returns a reversed copy of s.
func Reverse(s []int) []int {
	out := make([]int, len(s))
	for i, v := range s {
		out[len(s)-1-i] = v
	}
	return out
}
go
package props

import (
	"math/rand"
	"reflect"
	"testing"
	"testing/quick"
)

// A fixed seed makes the "random" inputs reproducible, so a failure found in
// CI can be replayed locally. Without Rand, testing/quick seeds from the clock.
func config() *quick.Config {
	return &quick.Config{MaxCount: 500, Rand: rand.New(rand.NewSource(1))}
}

// Property: reversing twice gives the original.
func TestReverse_Involution(t *testing.T) {
	prop := func(s []int) bool { return reflect.DeepEqual(Reverse(Reverse(s)), append([]int{}, s...)) }
	if err := quick.Check(prop, config()); err != nil {
		t.Error(err)
	}
}

// Properties of Split: the parts add up to the total, and no two parts differ
// by more than one cent. No example can say that for every input.
func TestSplit_Properties(t *testing.T) {
	prop := func(total uint32, n uint8) bool {
		if n == 0 {
			return true
		}
		parts, err := Split(int64(total), int(n))
		if err != nil || len(parts) != int(n) {
			return false
		}
		var sum, lo, hi int64 = 0, parts[0], parts[0]
		for _, p := range parts {
			sum += p
			lo, hi = min(lo, p), max(hi, p)
		}
		return sum == int64(total) && hi-lo <= 1
	}
	if err := quick.Check(prop, config()); err != nil {
		t.Error(err)
	}
}

func TestSplit_Examples(t *testing.T) {
	got, err := Split(100, 3)
	if err != nil || !reflect.DeepEqual(got, []int64{34, 33, 33}) {
		t.Errorf("Split(100, 3) = (%v, %v), want [34 33 33]", got, err)
	}
	if _, err := Split(100, 0); err == nil {
		t.Error("Split(100, 0) should fail")
	}
}

// FuzzSplit runs its seed corpus as ordinary tests under "go test", and the
// fuzzing engine explores further under "go test -fuzz=FuzzSplit" (Go 1.18).
func FuzzSplit(f *testing.F) {
	f.Add(int64(100), 3)
	f.Add(int64(0), 1)
	f.Add(int64(1), 7)
	f.Fuzz(func(t *testing.T, total int64, n int) {
		if total < 0 || n <= 0 || n > 1<<16 {
			return // outside the documented domain; checked BEFORE Split so a huge n cannot allocate
		}
		parts, err := Split(total, n)
		if err != nil {
			t.Fatalf("Split(%d, %d) error: %v", total, n, err)
		}
		var sum int64
		for _, p := range parts {
			sum += p
		}
		if sum != total {
			t.Fatalf("Split(%d, %d) sums to %d", total, n, sum)
		}
	})
}

PHP: Eris generators plus $this->forAll(...)->then(...) inside a PHPUnit test (expected, not run; its README was saved).

Snapshot and golden-file tests Good to know ​

In plain words: store the expected output once in a file; the test compares the current output with it and fails on any difference. Review a change by reading the diff of the file.

Common misunderstanding: "Snapshots are free coverage." They are cheap to write and easy to approve blindly: a reviewer who runs -update without reading the diff has turned the test into a rubber stamp. Snapshot only output that is stable and small enough to review.

Definition: in Go the idiom is a golden file under testdata/ and an -update flag; Pest has expect($response)->toMatchSnapshot(); Laravel and PHPUnit have community snapshot packages.

text
     Step  What happens
1    dev changes the receipt layout
2    TestRender_Golden fails and prints got versus want
3    dev runs go test ./golden -update; the golden file changes
4    the diff of receipt.golden.txt is reviewed in the pull request like code

Go (runs):

go
// Package golden shows golden-file (snapshot) testing for a text report.
package golden

import (
	"fmt"
	"strings"
)

// Item is one line of a report.
type Item struct {
	Name  string
	Qty   int
	Cents int64
}

// Render formats items as a fixed-width receipt.
func Render(items []Item) string {
	var b strings.Builder
	var total int64
	fmt.Fprintf(&b, "%-10s %3s %9s\n", "ITEM", "QTY", "AMOUNT")
	for _, it := range items {
		amount := int64(it.Qty) * it.Cents
		total += amount
		fmt.Fprintf(&b, "%-10s %3d %9s\n", it.Name, it.Qty, money(amount))
	}
	fmt.Fprintf(&b, "%-10s %3s %9s\n", "TOTAL", "", money(total))
	return b.String()
}

func money(cents int64) string { return fmt.Sprintf("%d.%02d", cents/100, cents%100) }
go
package golden

import (
	"flag"
	"os"
	"path/filepath"
	"testing"
)

// Run "go test ./golden -update" to rewrite the golden files, then review the
// diff in version control like any other code change.
var update = flag.Bool("update", false, "rewrite golden files")

func TestRender_Golden(t *testing.T) {
	items := []Item{{"pen", 3, 250}, {"notebook", 1, 1299}}
	got := Render(items)

	path := filepath.Join("testdata", "receipt.golden.txt")
	if *update {
		if err := os.WriteFile(path, []byte(got), 0o644); err != nil {
			t.Fatal(err)
		}
	}
	want, err := os.ReadFile(path)
	if err != nil {
		t.Fatalf("read golden file (run with -update to create it): %v", err)
	}
	if got != string(want) {
		t.Errorf("Render() differs from %s\n--- got ---\n%s--- want ---\n%s", path, got, want)
	}
}
txt
ITEM       QTY    AMOUNT
pen          3      7.50
notebook     1     12.99
TOTAL              20.49

Real scenarios: rendered e-mails, generated SQL, JSON API responses, CLI output, compiler or formatter output. Pitfall: dates, IDs and map order inside snapshots (see Flaky tests). The -update flag is defined in that one test package, so go test ./... -update fails in other packages; run it with the package path.

Testing in production: feature flags, canary, shift left Important ​

In plain words: some failures only appear with real traffic, so release gradually and watch. Shift left means finding problems earlier and cheaper; testing in production means accepting that some are found later and making that safe.

Common misunderstanding: "Testing in production means skipping tests." It complements them. Pre-production tests catch what you can predict; canaries and flags limit the damage of what you cannot.

Definition:

TechniqueWhat it doesSource
Feature flag (feature toggle)Ship code dark; turn it on for some users; turn it off without a deployFowler, Feature Toggles (saved)
Canary releaseSend a small share of traffic to the new version, compare metrics, then roll forward or backFowler, Canary Release (saved)
Shift leftMove checks earlier: types, linters, small tests on every commit, contract checks before mergeCommon term; Fowler's TIA article contrasts "shift right"
Observability and SLOsAlerts as the production-side test of the same requirementsSee the observability chapters
Synthetic checksA scripted smoke test that runs continuously against productionA large test, run on a schedule

Timeline of a canary:

text
     Step  Who        What happens
1    10:00 CI         all stages green; version 2.14 built
2    10:05 Deploy     2.14 receives 5 percent of traffic behind a feature flag
3    10:20 Monitor    error rate 0.2 percent, p95 latency +40 ms: within limits
4    10:25 Deploy     25 percent, then 100 percent at 10:50
5    11:10 Monitor    a rare failure for one customer segment: flag off in seconds, fix, retry

Real scenarios: a new payment provider enabled for 1 percent of orders; a database migration rolled out with dual writes; a risky UI change behind a flag. Laravel's own feature-flag package is Pennant (documented on laravel.com/docs/13.x/pennant); in Go a flag is usually a small interface over a config or flag service.

CI and speed: stages, parallelism, test impact analysis Important ​

In plain words: run the fastest, most informative tests first and often; run slower ones later and less often; spread the work over many processes; and skip tests that cannot have been affected.

Common misunderstanding: "A slow suite just needs a bigger machine." Often the suite has too many broad tests, shared databases and sleeps. Parallelism only helps tests that are isolated; shared state turns it into flakiness.

Definition:

Pre-commit / PRformat, lint, typessmall tests (unit)seconds, in parallelMerge buildmedium tests:DB, httptest, fakesminutes, shardedContractsprovider verification,can-i-deploy checkbefore every deployDeployed buildlarge tests: a fewsmoke / E2E journeyson stagingProductioncanary, feature flags,monitoring, rollbacktesting in productionQuarantine lane (outside the gate)flaky test detected -> removed from the gate, ticket filed, owner, deadlinefixed and returned, or deleted; retries only to measure, never to hideshift left: the earlier the stage, the faster and cheaper the feedback
StageContentsTypical timeGate
Pre-commit or pull requestFormat, lint, types, small testsSeconds to 2 minutesBlocks merge
Merge buildMedium tests (database, httptest), contract verification3 to 10 minutesBlocks merge or deploy
Deployed buildA few large tests, smoke tests on staging5 to 15 minutesBlocks promotion
ProductionCanary, flags, monitoring, synthetic checksContinuousTriggers rollback
QuarantineFlaky tests, tracked and time-boxedOff the gateNobody waits for it

The DORA capability page asks for suites that are fast and reliable and says "Keep the test suite fast. Developers should be able to get feedback from automated tests in less than ten minutes both on local workstations and from the continuous integration system.". The times above are typical, not from a source.

Parallelism:

ToolHowCondition
Gogo test can run several packages at once; t.Parallel() runs tests within a package in parallel; -parallel n caps itTests must not share state; t.Setenv forbids parallel
Laravelphp artisan test --parallel (needs brianium/paratest), --processes=4, --recreate-databasesOne test database per process, created and migrated automatically
Pest./vendor/bin/pest --parallelSame isolation rules; --profile finds slow tests
ParaTestvendor/bin/paratest: parallelise by test case, or --functional by testPHPUnit only
CI shardingSplit packages or test files across machinesNeeds balanced shards and artifacts

Test impact analysis (TIA): Paul Hammant's article on Fowler's site defines it as analysing "the call-graph of the source code to work out which tests should be run after a change to production code". It targets the case where there are "too many" tests to run before check-in. Alternatives in the same article: suites and tags, pre-calculated graphs of source against tests. Risk: a wrong graph skips a test that mattered, so full runs still happen on merge or nightly.

Timeline of a speed-up (a 28-minute suite):

text
     Step  Change                                        Suite time
1    baseline: everything sequential                     28 min
2    t.Parallel + isolated temp dirs + fake clock       19 min
3    transaction per test instead of migrate per test    11 min
4    shard into 4 CI jobs                                 4 min
5    TIA on pull requests, full run on main               under 2 min typical, 4 min on main

Real scenarios: a pull-request lane that runs -short plus affected packages and a main-branch lane that runs everything; a nightly mutation run on the pricing package. The pipeline mechanics (runners, caches, artifacts) are on CI/CD Pipelines.

Laravel testing: Feature versus Unit, Pest versus PHPUnit Important ​

In plain words: Laravel gives you two folders and two runners. Feature tests boot the whole application; Unit tests do not.

Common misunderstanding: "Unit tests in Laravel can use the database and the container." Laravel's docs say tests in tests/Unit "do not boot your Laravel application and therefore are unable to access your application's database or other framework services".

Definition (from the Laravel 13.x testing pages):

TopicWhat the docs say or show
Default layouttests/Feature and tests/Unit, each with an ExampleTest.php
Feature tests"may test a larger portion of your code, including how several objects interact with each other or even a full HTTP request to a JSON endpoint. Generally, most of your tests should be feature tests."
Runnersvendor/bin/pest, vendor/bin/phpunit or php artisan test; arguments pass through (--testsuite=Feature --stop-on-failure)
Environmenttesting environment from phpunit.xml; session and cache use the array driver; .env.testing is used instead of .env
DatabaseRefreshDatabase (transaction per test), DatabaseMigrations, DatabaseTruncation; Seed attribute for seeding
HTTP$this->getJson, postJson, actingAs, assertions such as assertOk, assertJsonPath, assertForbidden
Fakes and mocksHttp::fake, Http::assertSent, Http::assertSentCount, $this->mock, $this->spy, $this->partialMock
Parallelphp artisan test --parallel with ParaTest; per-process databases; ParallelTesting hooks
PestPHPUnit
Function style: it('does something', function () { ... }); expect($value)->toBe(...)Class style: public function test_...(): void; $this->assertSame(...)
pest()->use(RefreshDatabase::class) in tests/Pest.phpuse RefreshDatabase; inside the class
Datasets: ->with([...])#[DataProvider('name')] attribute
Built-ins: snapshots (toMatchSnapshot), mutation testing (--mutate), --parallel, --profile, --compactCoverage and risky-test reporting; mutation via Infection
Runs on top of PHPUnitThe base runner under both

Both styles can live in one project. The module's CheckoutFeatureTest.php (PHPUnit class style) and CheckoutTest.pest.php (Pest) test the same HTTP layer; lint only, not run here.

php
<?php

declare(strict_types=1);

use App\Models\Order;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;

// Pest version of a Feature test. pest()->use(...) normally lives in
// tests/Pest.php; it is repeated here to keep the file self-contained.
pest()->extend(Tests\TestCase::class)->use(RefreshDatabase::class);

it('lists only my orders', function () {
    $me = User::factory()->create();
    Order::factory()->for($me)->count(2)->create();
    Order::factory()->count(3)->create(); // somebody else's

    $this->actingAs($me)
        ->getJson('/api/orders')
        ->assertOk()
        ->assertJsonCount(2, 'data');
});

it('rejects a negative quantity', function (int $quantity) {
    $this->actingAs(User::factory()->create())
        ->postJson('/api/orders', ['sku' => 'pen', 'quantity' => $quantity])
        ->assertUnprocessable();
})->with([-1, 0, 10_001]); // a Pest dataset: one run per value

Design for testability Must-know ​

In plain words: code is easy to test when you can give it its inputs and see its outputs, without a clock, a network or a global in the way.

Common misunderstanding: "Hard-to-test code needs a better mocking tool." It needs a better seam. If a test needs reflection, a monkey patch or ten mocks, the design is telling you something; see the smells on Code Smells & Refactoring.

Definition: the usual seams.

ObstacleSeamGoPHP and Laravel
The clockA Clock argument or interfacehermetic.Clock; or testing/synctest for concurrent timeCarbon time-travel helpers; inject ClockInterface
Randomness and IDsPass the generator inSeeded rand.New(rand.NewSource(1))Seed Faker, or inject an ID generator
The network and third partiesAn interface at the consumer, implemented by an adapterSmall interface next to its user (DIP)Interface bound in the container; Http::fake at the edge
The databaseRepository interface plus a real-database test of the repositoryOrderRepo, MemRepo, dbtest.WithTxEloquent in feature tests with RefreshDatabase
Global state and singletonsPass dependencies explicitlyNo package-level mutable stateAvoid static calls in domain code; use the container
Mixed logic and I/OFunctional core, imperative shellPure Quote(...) plus a shell (Clean Code)Pure service class plus a thin controller
ConcurrencyMake waiting explicitEventually, synctest, -raceQueue fakes; run jobs synchronously in tests

Timeline of making code testable (a function that calls time.Now() and an HTTP API inline):

text
     Step  Change                                              Result
1    extract the pure rule from the handler                    the rule is a table test
2    pass the time in as an argument                           no sleeping, no date-flaky tests
3    define a PaymentGateway interface where it is used        a stub or fake replaces the HTTP client
4    keep the real adapter, test it once with httptest         adapter covered at medium size
5    the handler now has one integration test                  most logic lives in fast unit tests

Real scenarios: the order service in this chapter takes four interfaces; the TTLCache takes a clock; the repository code takes an Execer. The architecture-level version of the same idea (ports and adapters) is on Clean, Hexagonal & Component Principles.

Per-language and per-tool behaviour ​

NeedGoPHP and Laravel
Test runnergo test (standard library testing)PHPUnit; Pest on top of it; php artisan test wraps both
Table-driven testsSlice of cases plus t.Run (Go 1.7)#[DataProvider], Pest ->with([...]) datasets
Setup and teardownt.Cleanup (Go 1.14), t.TempDir (Go 1.15), t.Setenv (Go 1.17), TestMainsetUp, tearDown, Pest beforeEach, traits such as RefreshDatabase
DoublesHand-written fakes, spies and stubs; small interfaces at the consumercreateStub, createMock, Mockery through $this->mock, spy, partialMock, facade fakes
HTTP testsnet/http/httptest (NewServer, NewRecorder)$this->getJson, postJson, actingAs, Http::fake for outgoing calls
Database isolationTransaction helper, container per packageRefreshDatabase, DatabaseTransactions, DatabaseMigrations, DatabaseTruncation
Test dataBuilders, object mothers, testdata/Model factories, seeders
Flakiness tools-race, -shuffle (1.17), -count, t.Parallel, testing/synctest (1.25)Parallel runner with per-process databases; time-travel helpers; PHPUnit risky-test reports
Coverage-cover, -covermode, go tool cover (statements)PCOV (lines), Xdebug (lines, branches, paths)
Mutation testinggo-mutesting, gremlinsInfection; Pest --mutate
Property-basedtesting/quick, rapid, native fuzzing (1.18)Eris
SnapshotGolden files plus an -update flagPest toMatchSnapshot
BDDgodogBehat
Contract testspact-gopact-php
Real dependenciestestcontainers-gotestcontainers/testcontainers-php
ParallelPackage-level and t.Parallel--parallel with ParaTest
Sizes-short plus build tags or directoriesTest suites and groups; tests/Unit and tests/Feature

Mechanics: how to run, select and speed up tests ​

The go test flags that matter Important ​

From the go test help text saved for this chapter:

FlagEffect
-run regexpRun only matching tests; -skip regexp skips matching ones
-shortTells long-running tests to shorten or skip themselves (testing.Short())
-count nRun each test n times; -count=1 also bypasses the test result cache
-raceData race detector; with -race the default coverage mode is atomic instead of set
-shuffle off,on,NRandomise test order; on seeds from the clock, N fixes the seed; "the seed will be reported for reproducibility"
-parallel nMaximum number of tests marked t.Parallel() that run at once
-failfastStop after the first failure
-cover, -covermode set,count,atomic, -coverprofileStatement coverage
-fuzz, -fuzztimeNative fuzzing (Go 1.18)
-timeout dFail a package that runs too long (a runaway test must not hang CI)

Version facts used on this page, from the Go release notes: t.Cleanup (Go 1.14), t.TempDir (1.15), t.Setenv and -shuffle (1.17), native fuzzing (1.18), testing.T.Context and testing.B.Loop (1.24), testing/synctest (1.25; first available in 1.24 under GOEXPERIMENT=synctest). The module declares go 1.24 and was run with Go 1.27.4.

Laravel test commands Important ​

bash
php artisan test                                  # all tests, readable report
php artisan test --testsuite=Feature --stop-on-failure
php artisan test --parallel --processes=4         # needs: composer require brianium/paratest --dev
php artisan test --parallel --recreate-databases  # rebuild the per-process test databases
./vendor/bin/pest --parallel                      # Pest equivalent
./vendor/bin/pest --profile                       # list the slowest tests
./vendor/bin/pest --mutate --parallel             # mutation testing (needs Xdebug 3.0+ or PCOV)

A CI configuration for both stacks Must-know ​

An illustrative pipeline (GitHub Actions syntax; not run here, pin current action versions yourself). It encodes the stage order from the diagram: static checks and small tests first, medium tests next, slow audits off the critical path.

yaml
name: tests
on:
  push:
  pull_request:
  schedule:
    - cron: "0 3 * * *"   # nightly: small is skipped on this event, so medium and laravel (which need it) are skipped too
jobs:
  small:                       # seconds to two minutes: runs on every push
    if: github.event_name != 'schedule'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-go@v5
        with: { go-version-file: go.mod }
      - run: gofmt -l . | tee /dev/stderr | (! read)
      - run: go vet ./...
      - run: go test -short -race -count=1 ./...
  medium:                      # real PostgreSQL service container; blocks the merge
    needs: small
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:16
        env: { POSTGRES_PASSWORD: postgres }
        ports: ["5432:5432"]
        options: >-
          --health-cmd pg_isready --health-interval 5s --health-retries 10
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-go@v5
        with: { go-version-file: go.mod }
      - run: go test -race -count=1 -shuffle=on ./...
        env: { TEST_DATABASE_URL: "postgres://postgres:postgres@localhost:5432/postgres?sslmode=disable" }
  laravel:                     # Feature and Unit tests in parallel, one database per process
    needs: small
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: shivammathur/setup-php@v2
        with: { php-version: "8.3", coverage: none }
      - run: composer install --no-interaction --prefer-dist
      - run: php artisan test --parallel
  nightly-quality:             # slow audits: mutation testing and the flaky-test report
    if: github.event_name == 'schedule'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: echo "run gremlins / Infection here; publish the score, do not block merges"

How a flaky test is hunted Important ​

bash
go test -race -count=50 -run 'TestTTLCache' ./hermetic        # repeat one test 50 times
go test -shuffle=on -count=5 ./...                            # random order, five times; the seed is printed
go test -run 'TestX' -count=200 -cpu 1,2,8 ./pkg              # vary GOMAXPROCS
./vendor/bin/pest --parallel --profile                         # PHP: are parallel runs the trigger?

If a failure appears only in the suite and never alone, suspect shared state; only under load, suspect timing; only in CI, suspect the environment (time zone, locale, missing service). Record the seed, the order and the CI run id in the ticket.

The test review checklist ​

QuestionWhy it matters
Does the test name state the situation and the expected behaviour?A failure should read like a bug report
Would this test fail if the code were wrong? (Try a mutation by hand.)Tests that cannot fail are decoration
Does it assert on behaviour a caller can see, not on private steps?Refactoring must not break it
Is there one act and a clear arrange, act, assert shape?Readers find the point at once
Does it use the cheapest level that can fail for this reason?Push tests down (Vocke)
Are doubles used only at boundaries, and is each mock justified by an interaction requirement?Mocks everywhere restate the implementation
Does every fake have a contract test?Fakes drift from reality
Is time, randomness, order and the file system under the test's control?Hermetic means repeatable
Does it pass alone, in any order and in parallel?FIRST: Isolated, Repeatable
Is the failure message informative (input, got, want)?Saves debugging time
Does it avoid sleeps, network calls and shared fixtures?The three flakiness engines
Is test data created for this test with only the relevant details visible?Builders and factories
Did a bug fix come with a regression test?The bug cannot return silently
Is it a medium or large test that belongs in a slower stage?Keep the gate fast

Solving the classic problems ​

ProblemSymptomSolutionCost
Slow suiteNobody runs tests before pushingPush tests down, separate sizes, parallelise, transaction per test, TIA on pull requestsNeeds isolated tests first
Flaky suiteRed builds are rerun by habitFind the cause (time, order, async, remote, leak); quarantine with a deadline; never blanket-retryDiscipline and tooling
Brittle mock-heavy testsEvery refactor breaks testsPrefer state verification and fakes; mock only boundary interactions; test behaviourSome set-up code
Ice-cream cone (mostly UI tests)50-minute builds, constant flakinessAdd API and component tests, delete overlapping UI tests, keep a few smoke journeysA migration project
Untestable legacy codeNo seams, globals, clocks inlineCharacterisation tests first, then introduce seams step by stepSlow but safe
Tests that duplicate each otherChanging one rule breaks twenty testsPick one level per rule; share builders; delete duplicatesCourage to delete
Coverage gate gamingHigh numbers, escaped bugsReview uncovered lines; add mutation checks on critical modulesSlower nightly job
Shared staging environmentIntegrated tests fail for other teams' reasonsContract tests and component tests with stubsContract tooling

The mock-heavy test, step by step ​

text
     Step  What you see                                                What to change
1    a refactor that keeps behaviour breaks 14 tests               the tests assert on calls between private collaborators
2    each failing test sets up 6 mocks                             the unit has too many collaborators, or the test is too low-level
3    move the assertion to the outcome (state) where possible      use a fake repository and check what was saved
4    keep one mock for the interaction that is the requirement     "charge exactly once"
5    add a contract test for the fake and for the real adapter     the double cannot silently drift

The flaky test, step by step ​

text
     Step  Action
1    reproduce: -count=200, -race, -shuffle=on, vary CPUs
2    classify with Fowler's list: isolation, async, remote service, time, resource leak
3    fix the cause: fake clock, polling with a deadline, per-test data, sorted output
4    if the fix is not today: quarantine with an owner, a ticket and a deadline; the gate stays green
5    after the fix: return it to the gate; if no fix by the deadline: delete it

Choosing: which test for which situation ​

SituationRecommended testExtra techniqueReason
Pure business rule (price, tax, validation)Table-driven unit testProperty test for invariants; mutation check on the moduleCheapest, most precise
Application service that calls a gateway and sends mailUnit test with stub, spy, fakeOne mock if "exactly once" is a requirementVerifies orchestration without the network
Repository or SQLIntegration test against the real engineTransaction per test; testcontainers in CIDialect, constraints and mapping bugs are real
HTTP handler or controllerhttptest or Laravel feature testContract test for response shapeRouting, validation and serialisation together
Call to another team's serviceConsumer test against a stub plus a contractPact with can-i-deployAgreement without a shared environment
Event consumer or queue jobTest with a fake broker or the real one in a containerIdempotency test (deliver twice)See Testing Messaging
Concurrency-race, synctest, deterministic fakesStress with -countSleeps are flaky
Parser or codecFuzz and round-trip propertiesGolden files for known inputsInputs you did not imagine
Report or template outputGolden fileReview diffs carefullyCheap regression net
Critical user journeyFew end-to-end smoke testsRun on every deploy; synthetic check in productionProves wiring, not logic
Bug fixRegression test firstSmallest level that reproduces itThe bug cannot return
Risky rolloutCanary and feature flagAlerting on SLOsLimits blast radius
Legacy code without testsCharacterisation testsSeams, then refactorSafety before change

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

Monolith: one process, one database ​

The simplest strategy is the trophy in practice. A Laravel monolith keeps most tests as Feature tests that boot the app and use RefreshDatabase, with Unit tests for pure domain classes; a Go service keeps pure packages (rules, calculators) under table tests and a handful of httptest plus real-PostgreSQL tests for handlers and repositories. One CI job runs everything in under ten minutes. Example: a shop where Shipping, Quote and tax rules are pure and hammered with tables and properties, while checkout is covered by four feature tests that go through HTTP, validation, the database and a stubbed payment call.

Modular monolith and multiple databases ​

Modules get their own test suites and a rule: a module's tests may use its own database tables and the public interface of other modules, never their internals. A fake of another module's public interface (an in-memory PricingModule) keeps module tests fast, and a contract test that runs against both the fake and the real module keeps the fake honest. Architecture tests (a Pest arch() test or a Go import-restriction linter) can fail the build when a module reaches into another's internals; that is a design test, not a behaviour test. Example: orders and billing modules in one repository, each with a testing package that exports its fakes.

Microservices: what survives across a network ​

Shared staging environments and end-to-end tests become the bottleneck, which is where Spotify's honeycomb and Pact come from. Each service tests itself in isolation (component tests with its own database and stubbed neighbours) and proves compatibility through consumer-driven contracts verified in the provider's pipeline, with can-i-deploy guarding every release. Example flow for checkout calling rates:

text
     Step  Who                What happens
1    checkout CI        consumer test passes against the Pact mock server; pact published to the broker
2    rates CI           verifies every published pact against the real rates handler; result published
3    checkout CD        can-i-deploy checkout 2.14 to production? yes: verified against the rates version in production
4    rates CD           rates 3.0 renames a field: its verification fails; can-i-deploy answers no
5    both teams         add the new field, keep the old, migrate consumers, then remove the old
6    production         canary 5 percent with a feature flag; a synthetic smoke check runs every minute

Messaging adds its own cases (duplicate delivery, ordering, poison messages) covered on Testing Messaging; security checks join the pipeline as described on Secure SDLC.

Distributed data: replicas, caches and eventual consistency ​

Tests that assume read-your-writes break against replicas and caches. Strategy: test the consistency rules in the component that owns them (how long can the cache lag, what does the read path do on a miss), inject the cache and replica behaviour as fakes with configurable delay, and test convergence with polling (Eventually) rather than sleeps. Examples: a fake cache that returns stale values for N reads; a fake clock that expires TTLs; a replica fake that applies writes after a configurable number of operations. Chaos or fault injection in staging, and canaries in production, cover what fakes cannot. Real databases in containers expose retry behaviour that an in-memory fake hides (for instance serialization failures under CockroachDB or PostgreSQL SERIALIZABLE, SQLSTATE 40001).

Scaling path: 1x, 10x, 100x ​

ScaleTeam and codeStrategy
1x: one developer or team, one repositoryHundreds of testsgo test ./... or php artisan test before each push; no special infrastructure
10x: several teams, one monolith or a few servicesThousands of tests, 10 to 30 minutesSizes and stages, parallel runs, per-process databases, quarantine policy, coverage on changed lines
100x: many services and teamsTens of thousands of testsContract tests and a broker, test impact analysis, sharded CI, a flaky-test dashboard, canaries and feature flags, a platform team that owns the test infrastructure (Google's 2016 post describes a team dedicated to flakiness data)

Lab: a TDD cycle, a mutation, a flaky test and a database rollback ​

You work in the module that ships with this page. Nothing needs Docker or a database server: the database test uses an in-process recording driver, and the Laravel part is "expected, not run".

Part A: Go ​

Setup. Run from the repository root; Go 1.24 or newer (module declares go 1.24; this page was built with Go 1.27.4):

bash
cd docs/snippets/design/testing-strategy-tdd/go
gofmt -l .                       # prints nothing
go vet ./...
go test -race -count=1 ./...
# ok  academy/testing-strategy-tdd/builders
# ok  academy/testing-strategy-tdd/contract
# ok  academy/testing-strategy-tdd/dbtest
# ok  academy/testing-strategy-tdd/doubles
# ok  academy/testing-strategy-tdd/golden
# ok  academy/testing-strategy-tdd/hermetic
# ok  academy/testing-strategy-tdd/props
# ok  academy/testing-strategy-tdd/tdd

Experiment 1: size filter. The two contract tests are medium tests (localhost only):

bash
go test -short -count=1 -v ./contract | grep -E '^(--- |ok|PASS)'
# --- SKIP: TestConsumer_WorksAgainstTheContract (0.00s)
# --- SKIP: TestProvider_HonoursTheContract (0.00s)
# PASS
# ok  	academy/testing-strategy-tdd/contract	0.426s

Experiment 2: order independence.

bash
go test -count=2 -shuffle=on ./hermetic ./doubles
# ok  	academy/testing-strategy-tdd/hermetic	0.401s
# ok  	academy/testing-strategy-tdd/doubles	0.364s

Experiment 3: red first, in the tdd package. Open tdd/strcalc.go and disable the maxOperand branch in Add (replace if n <= maxOperand { with if true {) and run the tests; you should see the failure shown in The TDD loop. Restore the line. This is the moment Canon TDD calls "red": the test fails for the right reason.

Experiment 4: a mutation by hand. In a scratch copy, change o.Subtotal() >= freeShippingFrom to > in builders/order.go. The suite catches the mutant because the table has a row at exactly the threshold:

text
--- FAIL: TestShipping (0.00s)
    --- FAIL: TestShipping/gold_at_the_threshold_ships_free (0.00s)
        builder_test.go:43: Shipping() = 700, want 0 (subtotal 5000)
FAIL
FAIL	academy/testing-strategy-tdd/builders	0.362s

Delete that table row and rerun: the mutant now survives, which is what go-mutesting and gremlins automate (they were not run here; expected, not run).

Experiment 5: coverage as a finder.

bash
go test -count=1 -cover ./...
# ok  	academy/testing-strategy-tdd/builders	0.582s	coverage: 100.0% of statements
# ok  	academy/testing-strategy-tdd/contract	0.581s	coverage: 84.0% of statements
# ok  	academy/testing-strategy-tdd/dbtest	0.548s	coverage: 80.0% of statements
# ok  	academy/testing-strategy-tdd/doubles	0.548s	coverage: 94.7% of statements
# ok  	academy/testing-strategy-tdd/golden	0.547s	coverage: 100.0% of statements
# ok  	academy/testing-strategy-tdd/hermetic	0.553s	coverage: 91.9% of statements
# ok  	academy/testing-strategy-tdd/props	0.553s	coverage: 93.3% of statements
# ok  	academy/testing-strategy-tdd/tdd	0.548s	coverage: 100.0% of statements

Read the numbers as Fowler suggests: find the uncovered lines (go test -coverprofile=c.out ./dbtest && go tool cover -html=c.out) and ask whether you are worried about them. 100 percent for builders does not prove Shipping is right; experiment 4 does.

Experiment 6: fuzzing. Five seconds of the native fuzzer on props.Split, run in a scratch copy:

bash
go test ./props -run=NONE -fuzz=FuzzSplit -fuzztime=5s
# fuzz: elapsed: 0s, gathering baseline coverage: 3/3 completed, now fuzzing with 12 workers
# fuzz: elapsed: 5s, execs: 4913816 (940005/sec), new interesting: 13 (total: 16)
# PASS

Now break Split (give every part base and drop the remainder) and rerun: the fuzzer reports a minimal failing input and writes it under testdata/fuzz/FuzzSplit, which then runs as a regression test on every go test.

Experiment 7: golden file. go test ./golden -update rewrites golden/testdata/receipt.golden.txt; change a format string in Render and run go test ./golden to see the diff output.

Part B: Laravel (expected, not run) ​

No Laravel application, Composer project or PHPUnit is installed here, so these steps are not run; every PHP file was only syntax-checked with php -l. The files below are everything the two test files need; nothing else has to be written except the User relationship in step 2.

  1. Create the app and API scaffolding: composer create-project laravel/laravel shop, then php artisan install:api (this creates routes/api.php and enables the /api prefix; use whatever your Laravel 13 install command is if it differs).
  2. Copy the files into place and add the missing relationship to app/Models/User.php: public function orders(): HasMany { return $this->hasMany(Order::class); }.
Snippet fileCopy to
php/App/Models.php (class Order)app/Models/Order.php
php/database/create_orders_table.phpdatabase/migrations/2026_01_01_000000_create_orders_table.php
php/Factories/OrderFactory.phpdatabase/factories/OrderFactory.php
php/Policies/OrderPolicy.phpapp/Policies/OrderPolicy.php (auto-discovered for Order)
php/Http/OrderController.phpapp/Http/Controllers/OrderController.php
php/routes/api.phproutes/api.php
php/tests/CheckoutFeatureTest.php, php/tests/CheckoutTest.pest.phptests/Feature/

The controller calls Http::post('https://payments.example/charge', ...), which the tests replace with Http::fake(['payments.example/*' => ...]); no real gateway exists. Both tests use actingAs, so the routes use the default auth middleware.

php
<?php

declare(strict_types=1);

namespace App\Models;

use Database\Factories\OrderFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/** The Order model the factory and the tests need: relationship plus HasFactory. */
class Order extends Model
{
    /** @use HasFactory<OrderFactory> */
    use HasFactory;

    protected $guarded = [];

    protected $casts = ['express' => 'boolean'];

    /** @return BelongsTo<User, $this> */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }
}
php
<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

final class OrderController extends Controller
{
    /** GET /api/orders: only the caller's orders. */
    public function index(Request $request): JsonResponse
    {
        return response()->json(['data' => $request->user()->orders()->get()]);
    }

    /** POST /api/orders: validates input; 422 on a bad quantity. */
    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'sku' => ['required', 'string'],
            'quantity' => ['required', 'integer', 'min:1', 'max:10000'],
        ]);

        $order = $request->user()->orders()->create([
            'status' => 'pending',
            'total_cents' => $data['quantity'] * 1000,
        ]);

        return response()->json($order, 201);
    }

    /** POST /api/orders/{order}/pay: authorise, charge the (faked in tests) gateway, mark paid. */
    public function pay(Request $request, Order $order): JsonResponse
    {
        $this->authorize('pay', $order);

        $response = Http::post('https://payments.example/charge', [
            'order' => $order->id,
            'cents' => $order->total_cents,
        ])->throw();

        $order->update(['status' => 'paid', 'receipt' => $response->json('receipt')]);

        return response()->json(['receipt' => $order->receipt]);
    }
}
php
<?php

declare(strict_types=1);

namespace App\Policies;

use App\Models\Order;
use App\Models\User;

final class OrderPolicy
{
    /** Only the owner may pay an order. Laravel auto-discovers App\Policies\OrderPolicy for App\Models\Order. */
    public function pay(User $user, Order $order): bool
    {
        return $order->user_id === $user->id;
    }
}
php
<?php

declare(strict_types=1);

use App\Http\Controllers\OrderController;
use Illuminate\Support\Facades\Route;

Route::middleware('auth')->group(function () {
    Route::get('/orders', [OrderController::class, 'index']);
    Route::post('/orders', [OrderController::class, 'store']);
    Route::post('/orders/{order}/pay', [OrderController::class, 'pay']);
});
php
<?php

declare(strict_types=1);

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('orders', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->string('status')->default('pending');
            $table->unsignedInteger('total_cents');
            $table->boolean('express')->default(false);
            $table->string('receipt')->nullable();
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('orders');
    }
};
  1. Run php artisan test --testsuite=Feature; expected: green with SQLite in memory, each test inside a rolled-back transaction.
  2. Run php artisan test --parallel --processes=4 (needs composer require brianium/paratest --dev); expected: the same results, with test databases suffixed by process token.
  3. Make one test wrong (change 'paid' to 'pending' in assertDatabaseHas); expected: red with a message naming the table and the row.
  4. Install Pest and run ./vendor/bin/pest --mutate on a class you covered with covers(...); expected: a mutation score and a list of escaped mutants.
  5. Install Infection (composer require --dev infection/infection) and run vendor/bin/infection --threads=4; expected: MSI per file.

Common misconceptions ​

BeliefReality
The pyramid says integration tests are badIt says broad, UI-driven tests are slower and more brittle than focused ones; Fowler's footnote allows broad tests if they are fast, reliable and cheap
The trophy or honeycomb replaces the pyramidFowler argues the shapes mostly differ in what they call unit and integration; their "unit test" means solitary, their "integration test" means sociable
TDD means writing all the tests firstOne test at a time, from a test list (Canon TDD); refactoring is a step, not an extra
A mock is just a smarter stubA stub supplies answers and you assert on state; a mock holds expectations and you assert on interactions
100 percent coverage means the code is testedCoverage shows what ran; assertion-free tests reach 100 percent. Fowler would be "suspicious of anything like 100%"
Retrying flaky tests fixes themRetries hide the signal; Google's own 3-times-in-a-row flag "encourages developers to ignore flakiness"
In-memory SQLite equals PostgreSQL for testsDifferent types, constraints and locking; test critical repositories on the real engine
Unit tests in Laravel can hit the databasetests/Unit does not boot the application; use tests/Feature
One assertion per test means one assert callOne concept per test; several assertions about one outcome are fine
Shared fixtures keep tests DRYThey couple tests through hidden data; prefer builders and factories per test
End-to-end tests prove the system works, so write manyThey are the slowest and flakiest layer; keep a few journeys
BDD is CucumberCucumber is a tool for the third practice; discovery conversations are the value
Mutation testing replaces coverageIt complements it; it is slower, so run it on critical modules or changed files
Testing in production replaces pre-production testsIt limits the damage of what tests missed; it does not replace them

Cheat sheet ​

TopicWhat to remember
Levels and sizesUnit, integration, component, end-to-end are arguments; small, medium, large (no network, localhost only, anything) can be enforced
ShapesPyramid: many unit. Trophy: mostly integration. Honeycomb: integration of one service, few implementation-detail tests
DoublesDummy unused, stub answers, spy records, mock expects, fake works (shortcut); a fake needs a contract test
SchoolsClassicist (Detroit or Chicago): real collaborators and state. Mockist (London): mock collaborators and interactions
TDDTest list, one test, make it pass, optionally refactor, repeat; triangulate; simplest transformation first
Test shapeArrange act assert; name = situation plus behaviour; one concept per test; failure message with input, got, want
FIRSTFast, Isolated, Repeatable, Self-validating, Timely
Test dataBuilder or factory with a valid default and named states; avoid shared fixtures
DatabaseTransaction per test (RefreshDatabase, WithTx); real engine for repositories; testcontainers in CI
FlakyCause list: isolation, async, remote, time, leaks; quarantine with a deadline; retries only to measure
BDDDiscovery, formulation, automation; Given When Then in Gherkin; Cucumber, Behat, godog
ContractsConsumer writes the contract, provider verifies it, broker plus can-i-deploy gate releases
CoverageA finder of untested code, not a goal; line, branch (Xdebug), path; Google 60/75/90 guideline, per team
MutationInject faults, count survivors; Infection, go-mutesting, gremlins; run on critical or changed code
PropertiesState invariants; testing/quick, rapid, native fuzzing, Eris; examples still document intent
CIFast stages first, contracts before deploy, a few large tests last; parallel, shard, TIA; quarantine off the gate
ProductionFeature flags and canaries limit damage; synthetic smoke checks watch continuously
LaravelFeature boots the app, Unit does not; RefreshDatabase; Http::fake; --parallel; Pest or PHPUnit

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 — What is the difference between a stub, a spy and a mock, and when do you choose each? Must-know ​

Answer

Answer: All three are test doubles (Meszaros). A stub returns canned answers and you assert on the result or state. A spy is a stub that records calls so you can assert afterwards. A mock holds expectations about calls (which method, arguments, how often) and fails the test when they are not met. Choose a stub to steer the path, a spy for an outgoing effect such as an e-mail, and a mock only when the interaction itself is the requirement (charge exactly once). See Test doubles.

2 — Explain red-green-refactor and what people get wrong about TDD. Must-know ​

Answer

Answer: Write one failing test (red), change the code so it and all earlier tests pass (green), then optionally clean up the design with the tests as a safety net, and repeat from a list of scenarios. Beck's Canon TDD lists the mistakes: converting the whole list into tests at once, deleting assertions to pass, mixing refactoring into making the test pass, abstracting too soon. Fowler adds that neglecting the refactor step is the most common failure. See The TDD loop.

3 — Pyramid, trophy and honeycomb: how do they differ, and what is the catch? Must-know ​

Answer

Answer: The pyramid wants many unit tests and few UI tests; the trophy (Dodds) wants mostly integration tests on top of static analysis; the honeycomb (Spotify) wants mostly integration tests of one service with few implementation-detail tests. Fowler's 2021 article points out that the camps mean different things by "unit" and "integration" (solitary versus sociable), so the debate is largely about vocabulary. Whatever the shape, aim for fast, reliable tests that fail for useful reasons. See Test shapes.

4 — How do you deal with a flaky test? Must-know ​

Answer

Answer: Reproduce it (repeat, shuffle, race detector), classify the cause with Fowler's list (isolation, asynchronous behaviour, remote services, time, resource leaks), and remove the non-determinism: inject a clock, poll instead of sleeping, give each test its own data, sort output. If the fix cannot happen today, quarantine the test with an owner and a deadline so the main gate stays trustworthy, then fix or delete it. Blanket retries hide real failures. See Flaky tests.

5 — What does coverage tell you, and why is a coverage target dangerous? Must-know ​

Answer

Answer: Coverage tells you which lines (or branches, with the right tool) the tests executed, so it finds untested code. It says nothing about whether the tests assert anything; once a number is a target, people reach it with assertion-free tests. Fowler recommends using it to look at untested code and being suspicious of 100 percent; Google's guideline of 60, 75 and 90 percent comes with the advice to review the uncovered lines. Mutation testing is the stronger signal. See Coverage.

6 — What is a consumer-driven contract test and why use one instead of an end-to-end test? Important ​

Answer

Answer: The consumer writes down the requests and responses it relies on (a pact); the provider verifies it can satisfy them in its own pipeline, and a broker's can-i-deploy check blocks a release that breaks a verified consumer. Each side is tested alone, so no shared environment or full-system deploy is needed, and failures point at the exact interaction. See Contract tests.

7 — How do you isolate database tests, and what are the traps of transaction-per-test? Important ​

Answer

Answer: Wrap each test in a transaction and roll it back (Laravel's RefreshDatabase, a Go WithTx helper), truncate tables, or give each worker its own database. The traps: code that opens a second connection or commits escapes the rollback, DDL commits implicitly on MySQL, and hidden retries such as serialization failures never show up. Run critical repository tests against the real engine, for example with testcontainers. See Database tests.

8 — What is the London school versus Chicago school (mockist versus classicist) debate? Important ​

Answer

Answer: Classicists (called Detroit by Fowler, Chicago by many others) use real collaborators and check state, replacing only awkward ones. Mockists (London school) mock every collaborator with interesting behaviour and check interactions, which drives out interfaces but couples tests to the call structure. A pragmatic default: sociable tests inside a module, doubles at module boundaries, a mock only where the call is the requirement. See The two schools.

9 — What is mutation testing and how is it different from coverage? Important ​

Answer

Answer: A tool changes the code in small ways (mutants) and re-runs the tests; surviving mutants show assertions that are missing. The mutation score (MSI in Infection) measures how many mutants the tests killed, whereas coverage only measures what ran. Tools are Infection for PHP and go-mutesting and gremlins for Go; they are slow, so run them on critical or changed code. See Mutation testing.

10 — Laravel: when do you write a Feature test and when a Unit test, and Pest or PHPUnit? Important ​

Answer

Answer: Unit tests (tests/Unit) do not boot the application, so they suit pure classes; Feature tests boot it and can go through HTTP, middleware, validation and the database (with RefreshDatabase), and Laravel's docs say most tests should be feature tests. Pest and PHPUnit both work; Pest is function-style with datasets, snapshots and built-in mutation testing, and runs on PHPUnit. See Laravel testing.

11 — How do you make a slow suite fast without making it flaky? Important ​

Answer

Answer: Push tests down to cheaper levels, split by size, make tests isolated (per-test data, injected clocks), then parallelise (t.Parallel, php artisan test --parallel with one database per process), shard in CI and use test impact analysis on pull requests with a full run on main. Parallelising tests that share state creates flakiness, so isolation comes first. See CI and speed.

12 — What are test data builders and factories good for? Good to know ​

Answer

Answer: They create valid objects with sensible defaults so each test mentions only the detail it is about; when a new required field appears, one default changes instead of every test. Go uses builders or helper functions, Laravel uses model factories with named states and relationship helpers. They replace shared fixtures, which hide dependencies between tests. See Test data.

13 — What is shift left and what does testing in production add? Good to know ​

Answer

Answer: Shift left means finding defects earlier, with types, linters, fast tests and contract checks before merge, because earlier feedback is cheaper. Testing in production accepts that some failures only appear with real traffic and makes them safe with feature flags, canary releases, monitoring and quick rollback. They complement each other. See Testing in production.

Glossary ​

TermMeaning
Test pyramidPortfolio picture with many unit tests, fewer service tests and few UI tests (Cohn, Fowler)
Testing trophyDodds's shape: static analysis, a few unit tests, mostly integration tests, a few end-to-end tests
Testing honeycombSpotify's shape for microservices: mostly integration tests of one service
Unit testA fast, programmer-written test of a small unit
Integration testA test of pieces working together, often with a real dependency
Component testA test of one deployable component through its public interface
End-to-end testA test through the real entry point of the whole system
Acceptance testA test that states a requirement in the customer's terms
Smoke testA small post-deployment check that the system is alive
Regression testA test that pins a bug that was fixed
Subcutaneous testA test through the service layer, skipping the UI
Contract testA test of the messages between a consumer and a provider
Consumer-driven contractsContracts written by consumers and verified by providers
PactA consumer-driven contract testing tool with a broker and can-i-deploy
Pact BrokerStores pacts and verification results; answers compatibility questions
can-i-deployA broker check that a version is safe to deploy given verified pacts
Provider stateData set-up a provider needs to replay one pact interaction
Test doublesAny replacement of a production collaborator in a test
MeszarosGerard Meszaros, author of xUnit Test Patterns and of the test double vocabulary
DummyA double passed but never used
StubA double with canned answers
SpyA stub that records how it was called
MockA double with expectations that fails the test if they are not met
FakeA working but simplified implementation, for example an in-memory repository
State verificationAsserting on the outcome
Behaviour verificationAsserting on the interactions
Sociable testA unit test that lets real collaborators run
Solitary testA unit test that replaces all collaborators
London school vs Chicago schoolMockist (London) versus classicist (Detroit or Chicago) styles of TDD
Mockist vs classicistBehaviour verification with mocks versus state verification with real objects
TDDTest-driven development: tests drive the code in small steps
Red-green-refactorFail, pass, clean up; the TDD mantra
Test-firstWriting the test before the code it exercises
Test listThe scenarios you intend to cover, written before the first test (Canon TDD)
TriangulationAdding a second example so a constant answer must be generalised
Fake itReturning a constant to reach green, then generalising
Transformation priority premisePrefer the simplest code transformation that makes the next test pass
BDDBehaviour-driven development: collaborative examples that become executable checks
Given When ThenContext, action, outcome; the Gherkin step structure
GherkinThe plain-language format for scenarios
CucumberThe BDD tool family that runs Gherkin
BehatThe PHP implementation of Cucumber
godogThe Cucumber implementation for Go
Specification by exampleUsing concrete examples as the specification
ATDDAcceptance test-driven development: acceptance test first, then code
Test sizes small medium largeGoogle's resource-based classification of tests
FIRSTFast, Isolated, Repeatable, Self-validating, Timely
Arrange act assertSet up, perform one action, check the outcome
Test namingNames that state situation and expected behaviour
One assertion per conceptGroup assertions that describe one outcome; split unrelated behaviours
Table-driven testsOne test function over a table of named cases
Test data buildersObjects that build valid test data with overridable details
Object motherA function that returns a named ready-made example
FactoriesClasses that create test objects, for example Laravel model factories
Laravel factoriesEloquent model factories with definition(), states and relationships
FixturesThe state a test needs before it runs
RefreshDatabaseLaravel trait that runs each test in a transaction and migrates only if needed
DatabaseTransactionsLaravel trait that wraps each test in a transaction without migrating
PestA PHP test framework built on PHPUnit with a function-style syntax
PHPUnitThe standard PHP testing framework
go testThe Go command that builds and runs tests
TestcontainersLibraries that start real dependencies in containers for tests
In-memory fakes vs real dependenciesThe trade-off between speed and fidelity
Hermetic testsTests that control all their inputs: clock, data, order, network
Flaky testsTests that both pass and fail on the same code
Non-determinismBehaviour that differs between runs of the same code
Test quarantineMoving flaky tests out of the gate, with an owner and a deadline
RetriesRe-running failed tests; a measurement tool, not a cure
CoverageThe share of code executed by tests
Line vs branch coverageLines that ran versus decision outcomes that ran
Coverage targetsA numeric threshold on coverage; dangerous when used as a goal
Mutation testingInjecting small faults to check that tests detect them
Mutation score (MSI)Share of mutants killed by the tests
InfectionThe PHP mutation testing tool
go-mutestingA Go mutation testing tool
gremlinsA Go mutation testing tool for smallish modules
Property-based testingChecking properties over generated inputs, with shrinking
FuzzingFeeding generated inputs to find crashes and violations; native in Go 1.18
Snapshot testingComparing output with a stored expected output
Golden filesStored expected output files under testdata/
Test impact analysisRunning only the tests affected by a change
Test parallelismRunning tests concurrently across goroutines, processes or machines
CI pipeline stagesOrdered build stages from fast checks to slow tests to deployment
Shift leftFinding defects earlier in the lifecycle
Testing in productionVerifying behaviour in production safely, with flags, canaries and monitoring
CanaryA release to a small share of traffic before the rest
Feature flagsSwitches that enable code paths without a deploy
Characterisation testA test that records what legacy code does today
SeamA place where behaviour can be replaced without editing the code
Ice-cream coneAn inverted pyramid: mostly UI tests, few unit tests

References ​

Built by Morteza Negahi