The test pyramid balances confidence against speed by stacking fast unit tests at the bottom, focused integration and contract tests in the middle, and just a few end-to-end tests on critical flows at the top. Unit tests cover pure business logic in milliseconds, while integration tests with Testcontainers and WireMock verify real SQL, transactions, and serialization. Inverting it into an ice-cream cone of heavy E2E tests makes CI slow, flaky, and painful to debug. In thinner microservices, I actually favor a testing trophy—investing more in realistic integration tests rather than chasing artificial unit-test ratios.
Test doubles come in five flavors: a dummy just fills a parameter, a stub returns canned data, a fake is a lightweight working implementation like an in-memory store, a spy wraps a real object to record calls or selectively override methods, and a mock verifies specific interactions. The biggest trap I see in codebases is over-mocking internal collaborators. That couples tests to implementation details, so harmless refactors turn the build red while broken SQL or serialization slips through. I use real objects for domain logic, real containers at database boundaries, and save stubs or mocks for external APIs or side effects like notifications.
Key terms:test doubles, stub vs mock, fake implementation, over-mocking
Likely follow-up: "Why do experienced engineers advise against mocking types you don't own, like a JDBC connection or HTTP client?"
追问2 个
为什么说“不要 Mock 你不拥有的类型(Don't mock types you don't own)”?
I evaluate unit tests using the FIRST principles: Fast so they run in milliseconds, Isolated with no shared mutable state or ordering dependencies, Repeatable across local machines and CI regardless of clock or network, Self-validating with explicit pass/fail assertions, and Timely—written alongside features or bug fixes. With JUnit 5 and AssertJ, I structure every test around Arrange–Act–Assert, name methods after the expected behavior, and use @ParameterizedTest with @CsvSource to cover edge cases without copy-pasting. AssertJ's fluent assertions produce clear failure messages for values and exceptions alike, while keeping tests focused on public behavior rather than brittle private methods.
Key terms:FIRST principles, Arrange-Act-Assert, @ParameterizedTest, AssertJ, public behavior
Likely follow-up: "How do you decide when a private helper method is complex enough to extract into its own collaborator class for testing?"
@WebMvcTest loads only the web layer for routing, validation, and JSON checks; @DataJpaTest isolates JPA mappings and queries; and @SpringBootTest boots the full application context. When a Spring test suite balloons from one minute to fifteen, the usual culprit is busting Spring's test context cache. Mixing different @MockitoBean overrides, profiles, or @DirtiesContext across test classes forces Spring to restart the container repeatedly. To keep builds fast, I run pure domain tests without Spring at all and share one base integration class with a consistent profile and container setup so the context boots once.
Key terms:sliced tests, test context caching, @SpringBootTest, @DirtiesContext
Likely follow-up: "Why can calling save() and findById() inside @DataJpaTest miss real database mapping bugs?"
H2 is fast, but it creates a dangerous illusion of safety because it only approximates PostgreSQL or MySQL. Once your service uses vendor-specific features like JSONB, ON CONFLICT, SKIP LOCKED, or production Flyway migrations, H2 either fails outright or behaves differently on locking, isolation levels, and null handling. Testcontainers spins up the exact database version you run in production inside Docker, and Spring Boot's @ServiceConnection wires it up with minimal boilerplate. To avoid slow builds, you share a single singleton container across the integration suite—adding just a few seconds of startup while eliminating database dialect and semantic drift.
Calling a live third-party sandbox in CI is slow and flaky, while mocking the client interface with Mockito completely skips JSON serialization, timeouts, and retry wiring. Instead, I spin up WireMock on a local random port so our real HTTP client executes the full request pipeline. Using short test timeouts, I simulate slow responses to verify read timeouts, stateful scenarios like two 503s followed by a 200 to test Resilience4j retries and Idempotency-Key reuse, plus 429 rate limits and connection resets. For gRPC dependencies, I use an in-process gRPC server stub (InProcessServerBuilder) to test deadlines and status codes just as deterministically.
具体分两步:首先,消费方在自己的单测里用 Pact 的桩写明“我发什么请求、期望响应里有哪些字段和类型”,跑完自动生成一份契约上传到 Pact Broker。接着,提供方在自己的 CI 里拉下所有消费方的契约,对着自己本地的服务跑一遍验证。如果提供方不小心删掉了某个消费方正在用的字段,提供方的 CI 当场就会红,根本不用拉起几十个服务做联调。而且它还能反过来告诉提供方:某个废弃字段是不是已经没有任何消费方在用了,可以放心删。
Consumer-driven contract testing bridges the gap between brittle shared E2E environments and blind unit-test mocks. With a tool like Pact, each consumer defines only the request and response fields it actually depends on during its own tests and publishes that contract to a Pact Broker. The provider then pulls and verifies every consumer's contract independently in its own CI pipeline, with can-i-deploy gating releases. Neither service needs to be deployed together, yet breaking field renames or removals are caught before merge, and providers can safely see when deprecated fields have zero remaining consumers—though a few thin E2E smoke tests still complement it.
Flaky Test 指代码未改但测试时过时挂,最大危害是摧毁 CI 信任,让大家习惯点重跑而放过真 Bug。五大常见根因:Thread.sleep 等异步、共享可变状态或脏库、依赖真实时间时区、端口冲突、直连外网。治理靠技术(Awaitility、注入 Clock、数据隔离)加流程零容忍(发现即隔离限期修)。
在流程上,团队要对 Flaky 零容忍:一旦发现,先把这条测试隔离出去防止卡死全员合并,同时立高优单限期修掉,千万别靠给 CI 挂自动重试来掩盖问题。
English PitchEnglish · ~55s
A flaky test passes and fails unpredictably without any code change, and its real damage is cultural: once engineers start reflexively clicking re-run, real production regressions slip through. Most flakiness comes from five root causes—hard-coded Thread.sleep calls on async flows, shared mutable state or dirty databases, system clock and timezone assumptions, port collisions, and calls to live external environments. Technically, I fix them with Awaitility polling, injected Clock instances, random ports, and isolated data per test. At the team level, we treat flakiness with zero tolerance—quarantine it immediately and fix the root cause instead of papering over it with CI retries.
Key terms:flaky test, Awaitility, Clock injection, test quarantine
Likely follow-up: "Why is configuring CI to automatically retry failed tests three times usually an anti-pattern?"
追问2 个
怎么提前发现测试里隐藏的“执行顺序依赖”?
定期在 CI 里开启 JUnit 5 的 MethodOrderer.Random 随机打乱测试顺序跑一遍,隐藏的共享状态污染很快就会暴露。
为什么说“给测试自动重试 3 次”是治标不治本?
重试会把真正偶发但致命的并发竞态 bug 掩盖掉,同时拉长 CI 耗时,让代码库里的不稳定债务越积越多。
易踩坑
用 Thread.sleep(2000) 解决异步消费测试失败,结果只是把测试变慢且在高负载 CI 下依然偶发失败。
Non-determinism usually comes from hardcoding uncontrolled state inside business logic, so the fix starts with lightweight dependency injection. For time and randomness, I inject java.time.Clock and ID or random generators—using Clock.fixed or fixed seeds in tests to verify expirations in milliseconds. For concurrency races like inventory deduction, I coordinate worker threads with CountDownLatch (ready, start, and done) so they fire together, collecting thread exceptions via Future.get() to assert invariants reliably. For Kafka or SQS consumers, I unit-test the pure handler synchronously and use Testcontainers with Awaitility in integration tests to poll eventual database state instead of brittle Thread.sleep calls.
I automate formatting and lint checks in CI so code review focuses on high-impact risks machines miss. First, I check correctness, concurrency hazards, transaction boundaries, and backward compatibility across rolling deploys—especially API contracts and database migrations. Next, I look at security and production resilience like authorization checks, timeouts, idempotency, and observability, before reviewing readability and edge-case test coverage. For disagreements, I separate blocking issues from non-blocking nit comments, stay objective around trade-offs, defer to the code owner on reversible style calls, and document major architectural decisions in an ADR.
Key terms:backward compatibility, blocking vs nit, production resilience, ADR
Likely follow-up: "How do you handle a teammate who repeatedly submits huge 1,500-line pull requests?"
追问2 个
为什么大 PR(比如一次改 2000 行)对团队伤害很大?
评审者认知过载,只能走马观花直接点 Approve,导致 bug 溜进主干;而且冲突多、回滚粒度太大。应通过 Feature Flag 或先重构后加功能把大需求拆成多个小 PR。
有了 Feature Flag 以后,没完全做完的功能可以包在默认关闭的开关后面,每天小步合入主干、正常部署上线,对用户完全不可见。等准备好了,先只对内部员工打开验证,再按 1%、10%、50% 逐步放量;一旦监控看到错误率升高,后台点一下关掉开关,秒级止血,连重新发版都不用。
不过 Feature Flag 用不好也很容易踩坑,最大的问题就是开关债务。很多团队只管加开关、不管删开关,半年后代码里到处是嵌套的 if (flagA) { if (flagB) ... },组合状态根本测不过来,老开关里还埋着死代码。所以我的习惯是:发布类开关在创建时就标好过期时间并挂一张清理单,全量稳定运行一两周后立刻把开关和老分支删干净。另外也要注意,如果开开关后写了新格式数据,必须保证关开关后老代码也能兼容读取,否则紧急关开关反而会触发二次故障。
追问2 个
如果配置中心(如 LaunchDarkly / Unleash / Nacos)突然不可用,Feature Flag 应该怎么表现?