📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Tell me about a time a bug reached production even though the code had high test coverage, say 90%. What kind of bug was it, why didn't the tests catch it, and what did you change in your test strategy afterwards?

A real-world escaped defect despite high coverage: diagnosing why the suite missed it (mocked boundaries, missing contract and integration tests, weak assertions), the incident response, and the test strategy changes that followed.

Senior RealWorldScenario Advanced code-coverage contract-testing incident-response integration-testing test-strategy testing

🎯 Key points

  • Coverage shows code executed, not that behaviour or contracts were checked; a coverage threshold alone can't detect weak assertions
  • Typical escapes: boundaries that were mocked (serialisation, SQL, config, time zones), not logic
  • Root cause analysis: which test should have caught it, and why it didn't exist or didn't assert
  • Immediate mitigation (rollback or flag off), then a regression test that fails first
  • Strategy change: add the missing test type at that boundary (WebApplicationFactory integration, Verify snapshots, OpenAPI diff, PactNet contracts) across the codebase
  • Agree contracts with consumer teams (e.g. the mobile team) so their expectations are encoded as tests
  • Add mutation testing (Stryker.NET) where weak assertions were the cause; measure recurrence of the bug class afterwards
  • Blameless review; tell it with STAR and real numbers

⏱ 30-second answer

A strong answer picks a real bug where coverage looked good but a boundary wasn't tested, for example a JSON contract change: a global JsonStringEnumConverter was added, enums started serialising as strings instead of numbers, and an older mobile app version crashed on parse. Every line was covered, but tests mocked the HTTP layer or deserialised with the same options as the server, so nothing compared the wire format with what clients expect. Then explain the response: roll back, add a failing regression test, and change the strategy: response snapshot tests with Verify, an OpenAPI diff in CI, and contract tests with the main clients. The lesson to land: coverage measures execution, not whether the right things were asserted at the right boundary.

🗣 Full answer (senior)

How I would answer this in an interview

"The clearest example I have is a contract bug. At [company] we had a .NET API serving a mobile app and [two] partner integrations, with about 90% line coverage and a coverage gate in CI.

A developer added JsonStringEnumConverter globally in Program.cs so new enums would read nicely in the API docs. Every test passed. In production, OrderStatus went from 2 to \"Shipped\" on the wire, and [the Android app versions older than 4.2], which parsed it as an integer, crashed on the order history screen. We saw a spike in crash reports and a [12%] drop in successful order-history loads within [40 minutes]. I led the response: we rolled back via slot swap in about [ten] minutes, then looked at why 90% coverage hadn't helped. The answer was that coverage measured execution, not the contract. Our controller tests called handlers directly, and the few HTTP tests deserialised responses with the same JsonSerializerOptions as the server, so a round trip always succeeded. Nothing compared the wire format against what clients actually expected.

We fixed it properly in three steps. First, a regression test that asserted the raw JSON for that endpoint and failed on the bad build. Second, response snapshot tests with Verify for every public endpoint, so any change to the wire format is a visible diff in the PR. Third, an OpenAPI diff with oasdiff in CI that fails on breaking changes, and consumer-driven contract tests with the mobile team. [Result: no client-breaking contract changes in the following year.] The mistake I see is treating an incident like this as 'add one more unit test'. The real fix is adding the missing type of test at the boundary that failed."


Why high coverage missed it

Gap Why coverage didn't help
Handlers tested directly, not over HTTP Serialisation never ran in the test
HTTP tests round-tripped with server's own options Server and test agreed with each other, not with clients
No assertion on raw JSON shape Values checked, representation not
No contract with consumers Nobody encoded what the mobile app expected

Other common "covered but broken" escapes

Bug Missing test
EF Core query fine on in-memory provider, fails on SQL Server Integration test on a real database
DateTime.Now vs UTC around AEST/AEDT daylight saving change Tests with FakeTimeProvider and time-zone cases
Missing DI registration for a new handler WebApplicationFactory test per endpoint
Config key renamed, works locally from user secrets Options validation with ValidateOnStart plus smoke tests
Tests with no meaningful assertions Mutation testing (Stryker.NET)

The response, in order

  1. Mitigate: roll back or flag off; measure customer impact.
  2. Reproduce: write a test that fails on the bad build.
  3. Fix: correct the code; the test passes.
  4. Find the class of bug: which test type was missing?
  5. Change the strategy: add that type of test across the codebase, not just for this endpoint.
  6. Measure: track whether that class of incident recurs.

Production example

After adding Verify snapshots for [140] public endpoints and oasdiff in CI, the next quarter's PRs surfaced [six] unintended contract changes, all caught before merge. CI time rose by about 40 seconds.

🔍 What the interviewer is checking

Checks ownership, root-cause thinking about test gaps, and whether the candidate improves the system rather than patching one case.

Green flags

  • Explains why coverage didn't help (mocked boundary, weak assertions).
  • Clear incident response: mitigate, reproduce, fix.
  • Adds a new type of test or gate across the codebase.
  • Measures the effect afterwards.
  • Blameless tone.

Red flags

  • Blames a person or bad luck.
  • Solution is "raise coverage to 95%".
  • No concrete details or numbers; story sounds rehearsed and generic.

📚 Learn in depth

1. What coverage actually measures

 line coverage  = lines executed during tests / total lines
 branch coverage = branches taken / total branches

Neither says anything about assertions or about the environment the code ran in. A line that runs under a mock of the database is covered, but the SQL it would generate is not tested.

2. Where escaped bugs come from

In most incident reviews, escaped bugs cluster at boundaries:

 client <-> [serialisation] <-> API <-> [DI / config] <-> handler <-> [EF Core / SQL] <-> DB
                                                            |
                                                       [HTTP client] <-> third party
                                                            |
                                                       [clock / time zone]

Unit tests replace every bracketed boundary with a double, so they can't catch bugs that live there. That is why boundary tests (integration, contract, snapshot) give more protection per test for APIs.

3. Wire-format testing

Three complementary techniques:

Technique What it catches Tool
Response snapshot Any change to JSON output Verify (VerifyJson)
OpenAPI diff Breaking schema changes (removed fields, type changes) oasdiff, build-time OpenAPI generation
Consumer-driven contract Changes to what a specific consumer reads Pact (PactNet)

Snapshot tests are cheapest to add; contract tests carry the most meaning because consumers define them.

4. Running a blameless review

Ask "which test should have caught this, and why didn't it exist?" rather than "who broke it?". The output is a change to the system (tests, gates, analysers), not to a person.

5. Turning the lesson into a guard

  • A Roslyn analyser or architecture test that flags JsonSerializerOptions changes in Program.cs for extra review.
  • A PR checklist item: "Does this change the wire format?"
  • A CI gate on oasdiff breaking changes.

Try it yourself

  1. Add JsonStringEnumConverter to an API and see which of your tests fail. If none, you have this gap.
  2. Add a Verify snapshot test for one endpoint's raw JSON.
  3. Generate the OpenAPI document at build time and run oasdiff breaking between two commits.
  4. Pick your last production incident and write the test that would have caught it.
  5. Run Stryker.NET on a well-covered project and look at survivors.

💻 Code

The regression test that failed on the bad build, and the snapshot test added for every public endpoint:

namespace Orders.Tests.Contracts;

using System.Text.Json;
using Microsoft.AspNetCore.Mvc.Testing;
using VerifyXunit;
using Xunit;

public sealed class OrderHistoryWireFormatTests(WebApplicationFactory<Program> factory)
    : IClassFixture<WebApplicationFactory<Program>>
{
    [Fact]
    public async Task Order_status_is_serialised_as_a_number_for_existing_clients()
    {
        var ct = TestContext.Current.CancellationToken;
        var client = factory.CreateClient();

        // Read raw JSON: never deserialise with the server's own options here.
        var json = await client.GetStringAsync("/orders/history?customerId=demo", ct);
        using var doc = JsonDocument.Parse(json);
        var status = doc.RootElement[0].GetProperty("status");

        Assert.Equal(JsonValueKind.Number, status.ValueKind);
    }

    [Fact]
    public async Task Order_history_response_shape_is_stable()
    {
        var json = await factory.CreateClient()
            .GetStringAsync("/orders/history?customerId=demo", TestContext.Current.CancellationToken);

        // Any change to names, casing, types or enum representation shows as a diff.
        await VerifyJson(json).ScrubMember("placedAtUtc");
    }
}
# CI: fail on breaking OpenAPI changes compared with main
oasdiff breaking origin-main/openapi.json artifacts/openapi.json --fail-on ERR

⚠ Common mistakes

  • Mistake: Answering that the tests were fine and it was bad luck. Why it is wrong: the interviewer is looking for learning and ownership. Instead: name the gap in the suite and what you changed.
  • Mistake: Fixing the incident with one extra unit test. Why it is wrong: the class of bug remains everywhere else. Instead: add the missing type of test (integration, contract, snapshot) across the codebase.
  • Mistake: Raising the coverage target after the incident. Why it is wrong: coverage was already high; it measures the wrong thing. Instead: add assertions at boundaries, or mutation testing for weak assertions.
  • Mistake: Deserialising responses in tests with the server's own JsonSerializerOptions. Why it is wrong: round trips always succeed, so wire changes are invisible. Instead: assert raw JSON or snapshot it.
  • Mistake: Blaming an individual in the review. Why it is wrong: people hide mistakes and the system doesn't improve. Instead: blameless review focused on missing guards.
  • Mistake: Inventing numbers or details in the story. Why it is wrong: follow-up questions expose it quickly. Instead: use your real numbers, or give honest estimates and say so.
  • Mistake: Skipping prevention. Why it is wrong: the same bug class returns. Instead: add a CI gate, analyser or checklist item and measure recurrence.

🏛 Senior insight: trade-offs

Interviewers ask this to see whether you understand the difference between executing code and verifying behaviour, and whether you respond to incidents by improving the system. The best stories show a bug at a boundary, a crisp diagnosis of why the suite couldn't see it, and a change of strategy that covers the whole class of bug, with a measurable result.

Response to the escape When it fits Cost When not to
One regression test Always, as step one Minutes As the only change
New test type across the codebase (snapshot, contract, integration) Boundary bugs Days Pure logic bugs already well covered
Mutation testing Bugs that slipped past weak assertions CI time Code that is mostly I/O
Raise coverage threshold Rarely Low When coverage was already high

Afterwards, measure recurrence of that bug class and how many PRs the new guard catches; that's your evidence the change was worth it.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions coverage being misleading or weak assertions. Why: Checks whether the candidate knows how to measure test effectiveness beyond coverage.
    How to answer

    Code coverage tells you which lines ran during tests, not whether any test would notice if they were wrong. A test with no assertions still gives coverage. Mutation testing measures that directly: a tool makes small changes to your code, called mutants (> to >=, + to -, true to false, removing a statement), runs the tests against each, and expects at least one test to fail. A failing test kills the mutant; if all tests pass, the mutant survived, which shows a gap. Stryker.NET does this for C# via dotnet stryker and reports a mutation score with build-breaking thresholds. The trade-off is run time: it re-runs tests many times, so you scope it to core logic and use incremental --since runs.

  2. When: Candidate mentions an API contract or serialisation change breaking clients. Why: Checks how the candidate detects breaking API contract changes in CI.
    How to answer

    I make the committed build-time spec the contract and gate pull requests on it:

    1. Drift check: rebuild and fail if the generated spec differs from the committed one.
    2. Breaking-change check: oasdiff breaking compares the PR's spec with main and the last released spec, and fails on removed paths or properties, new required request fields, narrowed enums or changed types.
    3. Lint: Spectral rules for house style (operationIds, ProblemDetails errors, naming).
    4. Versioning: one document per major version (AddOpenApi("v1"), AddOpenApi("v2")), so breaking changes go into a new version while v1 stays frozen.

    The trade-off: CI becomes stricter and occasionally needs a deliberate override, but breaking changes become explicit decisions instead of production incidents.

  3. When: Candidate mentions adding contract tests with consumers. Why: Checks whether the candidate understands consumer-driven contracts vs end-to-end tests.
    How to answer

    A consumer-driven contract test checks one consumer-provider pair in isolation. The consumer's tests run against a Pact mock and record what it actually uses; the provider replays those expectations against its real code (dependencies stubbed) in its own CI. Because the provider must keep passing every consumer's contract, it can evolve and version its API without silently breaking anyone, which preserves team autonomy.

    An end-to-end test deploys many services together and drives a real user journey. It catches wiring, configuration and infrastructure problems contract tests can't, but it needs a shared environment, runs for minutes, fails for unrelated reasons and slows every deployment pipeline that waits on it.

    So: a contract test for every consumer-provider pair as the main safety net, and only a handful of end-to-end smoke tests for the few journeys that make money. The trade-off is fast, precise feedback versus realistic but slow, flaky coverage.

🛠 Real-world problems: how you handle them

Global enum converter breaks older mobile app versions despite 90% coverage
Situation
A .NET API on Azure App Service served a [retail] mobile app (iOS and Android) and [two] partner integrations, [N] requests a day. CI enforced 90% line coverage. Older app versions were still used by about [18%] of customers.
Signals
Within [40 minutes] of a release, crash reports in [Firebase Crashlytics / App Center] spiked on the order history screen for Android versions below [4.2]; Application Insights showed no server errors (all 200s) but successful order-history loads in the app fell [12%]; support tickets mentioned the app closing.
Investigation
Compared the raw JSON for `/orders/history` between the previous and current build using the staging slot: `status` changed from `2` to `"Shipped"`. Git diff showed `JsonStringEnumConverter` added globally in `Program.cs`. Reviewed tests: handler tests bypassed HTTP; the few `WebApplicationFactory` tests deserialised responses with the server's options, so they passed. No snapshot, OpenAPI diff or consumer contract existed.
Resolution
Immediate: swapped slots back to the previous build in about [10] minutes and confirmed crash rate returned to baseline. Then applied the converter only to new enums via attributes, added a failing regression test on the raw JSON, and released. Longer term: Verify snapshot tests for all public endpoints, oasdiff breaking-change gate in CI, and PactNet consumer contracts with the mobile team.
Prevention
oasdiff gate on every PR; snapshot tests reviewed as part of code review; PR checklist item "changes wire format?"; Application Insights alert on drop in successful client calls (custom event from the app), not only server 5xx.

How to tell it (STAR)

**S:** Our API had about 90% coverage, but a release crashed the order history screen for [older Android app versions], around [18%] of users. **T:** As [tech lead] I owned the response and the follow-up. **A:** We swapped slots back in about [ten] minutes. I found a global enum converter had changed `status` from a number to a string, and our tests never compared the raw JSON with what clients expected, because they round-tripped with the server's own settings. I added a failing regression test, then snapshot tests for every public endpoint, an OpenAPI breaking-change gate and consumer contracts with the mobile team. **R:** In the next quarter the new checks caught [six] unintended contract changes before merge, and we had [no] client-breaking releases in the following [year].

More in Test Types

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me