Writing the Failing Test First

Topics Covered

Why the Test Comes First

What a failing test proves

What happens when you test after

Why this matters more with assistant code

What interviewers notice

An example in Python

An example in TypeScript

An example in Java

The habit in one line

Test first is not test everything

When the test is hard to write

The cost of skipping it

A sample exchange

Summary

When you find a bug in assistant code, the instinct is to fix it straight away. The fix is often obvious, and the round is short. But fixing first and testing after, or not testing at all, leaves you unable to answer a simple question: did the fix change anything that matters? Writing a test that fails on the current code before you change it answers that question, takes a minute or two and changes how the interviewer sees your work.

This lesson covers why the failing test comes first, how to choose the inputs from the rule rather than from the code, how to write tests that fail for one clear reason, how to check the tests the assistant writes and how to fit the whole loop into a timed round.

A test that fails first proves it can detect the bug.

What a failing test proves

A test that fails on the old code and passes on the new code proves two things. First, the test can detect the bug: it exercises the faulty path and checks the right thing. Second, the fix addressed the bug: something that was wrong is now right. Neither of these is proved by a test that passes on both versions.

This sounds obvious, but it is easy to get wrong. A test can pass for reasons that have nothing to do with the fix: it checks the wrong output, it uses an input that never reaches the buggy line, it compares against a value copied from the buggy output or its assertion is never reached. Watching it fail first rules all of these out at once.

What happens when you test after

A test written after the fix may pass for the wrong reason.

When you write the fix first and the test after, the test passes immediately, and you feel finished. But you do not know whether it would have failed before. If it would not have, the test protects nothing, and the fix is unverified. You find out later, when a hidden check fails on the case you thought you had covered.

The fix may also be wrong in a way the test cannot see, because the test was shaped by the fix. You wrote the fix, so you know what it handles, and the test checks exactly that. A test written from the rule, before you know the fix, checks what the rule demands instead.

Why this matters more with assistant code

With assistant code, you did not write the bug, so your understanding of it comes from reading and reasoning. Reasoning can be wrong. A failing test turns your reasoning into evidence: this input gives this wrong result. If the test does not fail, your reasoning was wrong, and you have learned that before spending time on a fix for a bug that does not exist.

Assistants also fix bugs when you ask, and their fixes can be wrong or partial. A failing test you wrote before asking gives you an objective check on the assistant's fix. Run it after the change. If it is still red, the fix did not work, whatever the assistant said.

What interviewers notice

Interviewers notice candidates who write a failing test first, because it is a habit of experienced engineers and it makes the candidate's reasoning visible. When you say I expect this input to return minus one and it currently returns twelve; here is a test that shows that, the interviewer knows you have found a real bug and how you will know it is fixed. That is a much stronger signal than a silent edit followed by the tests still pass.

An example in Python

The rule: a version string is three non negative integers separated by dots, such as 1.4.10. Return the tuple of three integers, or None if the string is not valid.

python
1def parse_version(s):
2    parts = s.split(".")
3    if len(parts) != 3:
4        return None
5    return tuple(int(p) for p in parts)

Reading it, you suspect that 1.-2.3 is accepted, because int of minus two succeeds, and that 1..3 crashes, because int of an empty string raises. Before fixing, write the tests:

python
1def test_rejects_negative_part():
2    assert parse_version("1.-2.3") is None
3
4def test_rejects_empty_part():
5    assert parse_version("1..3") is None

Run them. The first fails because it returns a tuple with a negative number. The second fails with a ValueError instead of returning None. Both failures confirm your reading, and both tests will tell you when the fix works.

An example in TypeScript

The rule: a coupon code is two to four uppercase letters followed by a dash and two digits, such as SAVE-10. Return true for valid codes.

typescript
function isCoupon(s: string): boolean {
  return /[A-Z]{2,4}-\d{2}/.test(s);
}

You suspect the regular expression is not anchored, so XSAVE-100 matches. Test first:

typescript
test("rejects extra characters around a valid code", () => {
  expect(isCoupon("XSAVE-100")).toBe(false);
});

It fails, confirming the suspicion. Anchoring the pattern with start and end markers makes it pass.

An example in Java

The rule: a date range string is two ISO dates separated by a slash, and the end must not be before the start.

java
1static boolean validRange(String s) {
2    String[] p = s.split("/");
3    return p.length == 2 && p[0].compareTo(p[1]) <= 0;
4}

The comparison works for valid ISO dates, but nothing checks that the parts are dates. Test first: validRange of hello slash world should be false. It returns true. Now you know what to fix.

The habit in one line

Before changing code to fix a bug, write a test that fails because of the bug, run it and watch it fail. Then fix, and watch it pass.

Test first is not test everything

Writing the failing test first does not mean writing a full test suite before any code. It means that for each bug you intend to fix, the test that demonstrates it exists and has been seen to fail before the fix. You can still write code freely, explore, and ask the assistant for drafts. The discipline applies at the moment you decide something is a bug and set out to change it.

When the test is hard to write

Sometimes the bug is hard to express as a test: it depends on timing, on external state or on a large input. In those cases, find the smallest reproduction you can. For a timing bug, a fake clock. For external state, a stub. For a large input, a generator with a fixed seed. If no test is practical in the time available, say so and describe how you would test it, then make the fix carefully. But this is the exception. Most interview bugs are a single input and a single expected value.

The cost of skipping it

The cost of skipping the failing test is not usually visible straight away. The fix looks right, the visible tests pass and you move on. The cost appears later: a hidden check fails on the case you thought you had fixed, or a later change reintroduces the bug and nothing catches it, or the interviewer asks how you know the fix works and you have no answer beyond it looks right. A minute spent on the failing test avoids all three.

A sample exchange

Interview Dialogue

CandidateI think this function accepts a negative quantity, which the rule forbids. Before I change it, a test: order of minus one items should be rejected.
CandidateRunning it. It fails: the order is accepted with a negative total. So the bug is real.
CandidateNow the fix, a guard on quantity at the top. Running the test again: it passes, and the rest of the suite is green.

The exchange took three lines. The interviewer saw the suspicion, the evidence and the verification, in that order.

Summary

A failing test proves the test detects the bug and the fix addresses it. Testing after the fix proves neither. With assistant code, the failing test also turns your reasoning into evidence and gives you an objective check on any fix the assistant proposes.

A test that never failed proves nothing

If a test passes before and after your fix, it does not detect the bug and does not verify the fix. Run it on the old code first. Red, then green, is the whole point.