Lesson · Testing
Testing Fundamentals
65 min readTesting Fundamentals
Tests provide executable evidence about behavior. Effective tests focus on externally meaningful outcomes, boundaries, and failure cases rather than mirroring the internal implementation line by line.
Learning goals
- Write a unit test that exercises one behavior with a plain
assertand explain what makes the tested unit coherent. - Separate Arrange, Act, and Assert so a failing test says which stage broke.
- List the edge cases a string-processing function needs before looking at its code: empty input, extra whitespace, mixed case, and invalid types.
- Explain what an integration test buys and costs compared with a unit test, using one real boundary.
- Say why test isolation matters: order-independent results, no shared state, deterministic inputs.
Mental model
The two test sizes answer different questions, and isolation decides whether an answer stays trustworthy: a test that depends on another test's leftovers or on today's clock can pass and fail without the code changing.
Mental model
read it top to bottom
unit test small behavior, controlled dependencies fast, points at one cause integration test components meet a real boundary slower, broader confidence Arrange → Act → Assert every test reads in this order happy path + edge cases empty, single item, limits, invalid input
Core idea
Tests are executable evidence: each one states a behavior, performs it, and checks an observable result, so the suite either confirms the contract or points at the piece that broke. Unit tests keep the scope small and dependencies controlled, integration tests cross a real boundary for broader confidence, and isolation keeps every result repeatable on its own. Write tests about what the code promises to callers, not about how it happens to be written today.
Unit tests
A unit test exercises a small behavior with controlled dependencies. The useful unit is a coherent behavior contract, not necessarily one function or class method.
Integration tests
An integration test checks that components work together across a real boundary such as a database adapter, filesystem, or HTTP layer. It trades speed and isolation for broader confidence.
Isolation
Isolation keeps a test independent of other tests and of uncontrolled external state: each test sets up what it needs and leaves nothing behind that later tests rely on. Slow, shared, or non-deterministic dependencies such as files and clocks get replaced or scoped per test so a failure points at one behavior.
Arrange-Act-Assert
Arrange creates the test state, Act performs the behavior under test, and Assert checks the observable result. The pattern keeps each test's purpose easy to scan.
Edge cases
Edge cases live at boundaries: empty input, one item, maximum/minimum values, duplicate data, invalid encodings, cancellation, or unavailable resources. Tests should make these explicit.
Walkthrough
normalize_namesplits on runs of whitespace, capitalizes each part, and joins with single spaces, so" ada lovelace "collapses to"Ada Lovelace"; the function has no dependencies to control.test_normalize_nameholds two assertions: the first covers the trimming and capitalization behavior, the second pins the empty-input edge where"".split()returns[]and" ".join([])is"".- The test is called explicitly and prints
"tests passed"only if both assertions hold; a failing assertion raisesAssertionErrorand stops the script, the plainest possible test runner. - Predict before running: the output line, what
normalize_name("ADA")returns, and what happens atNone.split()whenNonereaches the function.
Experiments to try
- Add
assert normalize_name("ada") == "Ada"andassert normalize_name("ADA") == "Ada"; then deletecapitalize()from the pipeline and watch both assertions fail. - Add the single-character case
assert normalize_name("a") == "A"and the tab-separated caseassert normalize_name("ada\tlovelace") == "Ada Lovelace"; explain why both pass with no extra code. - Predict, then verify, the exact value of
normalize_name(" ada "); write the assertion from the contract rather than from the implementation. - Split the two assertions into separate test functions,
test_trims_and_capitalizesandtest_empty, and run both; explain why smaller failures are easier to place.
Common mistakes
- Mirroring the implementation in the assertion: when the expected value is computed with the same expression as the function, a wrong function and a wrong expectation agree with each other; write literals from the contract instead.
- Depending on test order or shared state: a test that relies on data another test left behind fails when run alone and hides which behavior actually broke.
- Testing only the happy path:
normalize_name("ada")passes while empty input, whitespace runs, andNonestay unexamined until production finds them. - Treating a real database or network call as a cheap check: the test becomes slow and non-deterministic and belongs at the integration level, not next to the string unit that runs in milliseconds.
Practice: Easy
- Run the worked example, then add
assert normalize_name("ada") == "Ada"; confirm it passes, then change the expected value to"ada"and read theAssertionErroroutput. - Add an assertion for
normalize_name(" "); state the expected result before running, then verify it. - Call
normalize_name("ada lovelace")andnormalize_name(" ADA ")and turn both results into assertions.
Practice: Medium
- Split
test_normalize_nameinto two functions, one per behavior (whitespace and capitalization, empty input), call both, and explain what becomes clearer when one of them fails. - Rewrite one test so Arrange, Act, and Assert are each one clearly separated block; state what belongs in the Act line and what belongs in Arrange.
- Add three edges to the normalize tests, a tab-separated name, a single letter, and a name that is already normalized; state which of the three the current implementation handles for free and why.
Practice: Hard
- Build a
run_tests(*functions)helper that calls each test function, counts passes, catchesAssertionErrorto report failures, and returns a nonzero status when anything failed; run it on the worked tests. - Failure lab: create two order-dependent tests where one fills a module-level list and the other expects it empty; run them forward and reversed and explain how the shared state changes the verdict.
- Explain why
normalize_nameneeds only unit tests today, then describe a real boundary (names read from a file or command line) and what an integration test for it would need that the current unit test does not.
Lesson checklist
- I can write a unit test for one behavior with a plain
assertand a literal expected value. - I can point at the Arrange, Act, and Assert lines in a test I wrote.
- I can list the edge cases a string-processing function needs before looking at its code.
- I can explain what an integration test trades away and why isolation keeps results reproducible.
Remember
A test states one behavior, performs it, and checks an observable result, so the suite either confirms the contract or names the piece that broke. Keep units small and dependencies controlled, add integration tests when components meet a real boundary, and isolate every test from shared state and from other tests. Write expected values as literals from the contract, because a test that mirrors the implementation agrees with its bugs.
Interview angles
What is the main purpose of **Unit tests**?+
A unit test exercises a small behavior with controlled dependencies. The useful unit is a coherent behavior contract, not necessarily one function or class method.
What should you pay attention to when using **Integration tests**?+
An integration test checks that components work together across a real boundary such as a database adapter, filesystem, or HTTP layer. It trades speed and isolation for broader confidence.
How does **Isolation** fit into this lesson?+
Isolation keeps a test independent of other tests and of uncontrolled external state: each test sets up what it needs and leaves nothing that later tests rely on. Slow or shared dependencies such as files and clocks get replaced or scoped per test so a failure points at one behavior.
Why can an assertion that recomputes the expected value with the same expression as the function fail to catch a bug?+
The assertion mirrors the implementation, so a wrong function and the wrong expectation agree with each other; the test notices only that the code changed, not that it is incorrect. Write the expected value as a literal taken from the contract.