Skip to content
Tutorials Center
My learning

Topics

Lesson 62 of 77 ยท DevOps, Tools and System Design

Testing and Code Quality Questions

Answer testing interview questions with confidence: unit vs integration tests, mocks vs stubs, TDD, flaky tests and code review, with runnable examples.

Almost every software interview touches testing, even when the job title never mentions it. Interviewers use it to learn how you think about risk: what can break, how you would know, and how much confidence is enough. A candidate who can explain why a test is flaky, or when a mock hides a bug, sounds like someone who has shipped real software.

This lesson walks through the questions that come up most often: the kinds of tests, test doubles, test-driven development, flaky tests and code review. The examples are plain JavaScript that you can run in the editor. The ideas are the same in Jest, JUnit, pytest or any other framework; the framework is only syntax.

What is the difference between unit, integration and end-to-end tests?

A unit test checks one small piece of logic, such as a function or a class, in isolation. It is fast (milliseconds), deterministic and pinpoints the failure. An integration test checks that several real parts work together: your code with a real database, a real HTTP layer or a real queue. It is slower and catches wiring mistakes that unit tests cannot see. An end-to-end test drives the whole system the way a user does, usually through a browser or a public API. It is the most realistic, the slowest and the most fragile.

Three levels of tests

Unit One function, no outside world. Milliseconds.
Integration Real parts together, like code plus database.
End-to-end The whole app, like a user.

Higher up means more realism, but slower and flakier.

1 / 2

The usual answer is the test pyramid: many unit tests, fewer integration tests and a handful of end-to-end tests. A good follow-up is that the shape is a guideline, not a law. A service that is mostly glue between a database and an API may deserve more integration tests than unit tests, because the logic worth testing lives in the queries.

What makes a good unit test?

A good test is fast, isolated, repeatable and readable. It fails for one reason, and the failure message tells you what broke. The standard structure is arrange, act, assert: set up the inputs, call the code once, check the result.

Two habits separate good tests from brittle ones. First, test behavior, not implementation. If you rename a private helper and ten tests fail, those tests were coupled to the wrong thing. Second, name tests as sentences: rejects an empty cart beats test1.

The editor below has a tiny test runner so you can see the pattern without any library. Notice that each test builds its own data and never shares state.

JS A tiny test runner: arrange, act, assert

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last test fails, and the message says exactly why. That is the quality to aim for: when something goes red, you should know what to fix without opening a debugger.

What is the difference between a mock, a stub and a fake?

These are all test doubles: stand-ins for a real dependency. People use the words loosely, and interviewers know it, so show that you understand the distinction and then say which one you would reach for.

  • A stub returns canned answers. It exists so the code under test has something to call. You do not check how it was used.
  • A mock records how it was called, and the test asserts on those calls ("was send called once with this address?"). It verifies interaction.
  • A spy wraps a real object and records calls while still doing the real work.
  • A fake is a working but simplified implementation, such as an in-memory repository instead of a real database.
JS Stub, mock and fake side by side

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A common trap question: "Can you over-mock?" Yes. If every dependency is mocked, the test only proves that your code calls the mocks the way you wrote it. It passes while the real database query is wrong. Mock the boundaries you do not own or that are slow (network, clock, payment provider) and use real objects or fakes for everything else.

What is test-driven development?

TDD is a loop with three steps: red (write a failing test for the next small behavior), green (write the least code that passes) and refactor (clean up while the tests protect you). The tests come first, so the design is shaped by how the code is used.

Honest benefits: tight feedback, fewer untested paths and APIs that are easy to call. Honest costs: it is slower at the start, awkward for exploratory work where you do not yet know what you are building, and weak tests written first are still weak tests. A balanced answer says you use TDD where requirements are clear, such as parsers, pricing rules and bug fixes (write the test that reproduces the bug first), and write tests soon after the code elsewhere.

When asked "do you do TDD?", avoid both "always" and "never". Describe when it pays off and give one concrete example from your work.

What is a flaky test and how do you fix it?

A flaky test passes and fails on the same code. Flakiness is worse than a failing test, because teams learn to ignore red builds, and then real bugs slip through. The root causes are few:

  • Time: tests that depend on the current date, a timezone or sleep(2) guessing how long something takes.
  • Randomness and ordering: unseeded random data, or tests that pass only when run in a certain order.
  • Shared state: a database row, file or global variable left behind by another test.
  • Concurrency: race conditions between the test and background work.
  • External services: real network calls that time out.

The fixes follow from the causes: inject a clock, seed random generators, give every test its own data and clean up, wait for a condition instead of a fixed delay, and replace real network calls with fakes.

JS A flaky test, then a fixed one

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The fix is dependency injection: the function receives its source of randomness, so a test can pin it. The same trick works for clocks, ID generators and HTTP clients. Also mention that you never just "retry until green" as a long-term answer: retries hide the bug, and a quarantine list with an owner and a deadline is a better stopgap.

What do you look for in a code review?

Interviewers ask this to see whether you can improve a codebase without being unpleasant. A strong answer has a priority order:

  1. Correctness: does it do what the ticket says, including edge cases and error paths?
  2. Tests: do they cover the new behavior and the likely failures?
  3. Design: is the change in the right place, with clear names and small functions?
  4. Risk: security, performance on large data, migrations and backward compatibility.
  5. Style: only what a linter cannot already enforce.

Then add the human side. Review the code, not the person. Ask questions ("what happens if this list is empty?") rather than issuing orders. Separate must-fix comments from nits. Keep pull requests small, because reviewers find far fewer problems in a 1,500-line diff. And when your own code is reviewed, thank people, explain your reasoning once, and do not defend a mistake.

How do you measure test quality?

Code coverage shows which lines ran during tests. It is useful for finding code that is never tested, but it cannot show that the tests check anything. A test that calls a function and asserts nothing gives 100% coverage and zero protection. Better signals are whether bugs found in production would have been caught, how quickly the suite runs, and how often it flakes. Mutation testing, which makes small changes to your code and checks that some test fails, measures assertion strength directly, though it is slow.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A test passes alone but fails when the whole suite runs. What is the most likely cause?

    Order-dependent failures usually come from shared state such as a database row, a file or a global variable. Give each test its own data and clean up.
  2. 2. Which test double is mainly used to verify that a method was called with specific arguments?

    A mock records interactions so the test can assert on them. A stub only returns canned values, and a fake is a simplified working implementation.
  3. 3. In TDD, what comes right after you see a test fail for the right reason?

    The loop is red, green, refactor. After red you write the smallest change that gets to green, and only then clean up.
  4. 4. Why can 100% line coverage still leave bugs undetected?

    Coverage measures what executed, not what was verified. A test with no meaningful assertion executes code but protects nothing.
  5. 5. Your pricing service mostly runs SQL queries with little other logic. Which mix of tests is most sensible?

    When the risk lives in the queries, mocking the database proves nothing. Integration tests with a real database catch the actual mistakes.

Summary

  • Unit tests are fast and isolated, integration tests check real parts together, end-to-end tests mimic users; the pyramid is a guideline.
  • Good tests follow arrange, act, assert, test behavior rather than implementation, and have clear names.
  • Stubs return values, mocks verify calls, fakes are simplified working versions; avoid over-mocking.
  • TDD is red, green, refactor; be honest about where it helps and where it does not.
  • Flaky tests come from time, randomness, shared state, concurrency and external services; fix the cause instead of retrying.
  • Review for correctness, tests, design and risk first, and stay kind. Coverage shows what ran, not what was checked.

Next: Behavioral Questions and the STAR Method.