Notes
What a unit is
A unit test checks one small piece of logic, a function, a method, or a small class, on its own. No database, no network, no browser, no real clock and no randomness, so it runs in milliseconds and gives the same answer every time. A useful test of your understanding: if a test needs ShopRung to be running, it is not a unit test. It is an integration or API test, which the next parts cover.
- checks one unit: a function, a method, a small class
- alone: no database, no network, no browser, no clock, no random
- runs in milliseconds
- not a unit test: anything
- that needs ShopRung running
Good unit tests
Good unit tests follow FIRST. Fast: milliseconds each. Isolated: no shared state, so they pass in any order. Repeatable: the same result on every run and every machine. Self checking: they say pass or fail, nobody reads logs to decide. And timely: written with the code, not months later. Add one more rule: each test should have one reason to fail, so a red test tells you exactly which behaviour broke.
- Fast: milliseconds
- Isolated: no shared state, any order works
- Repeatable: same result every run, every machine
- Self-checking: pass or fail, no reading logs
- Timely: written with the code
- + one reason to fail per test
JUnit 5
Here is ShopRung's save ten rule tested in JUnit five. A parameterized test feeds four rows: forty nine ninety nine gets no discount, fifty dollars gets five hundred cents, fifty oh four still five hundred, and fifty oh five gets five hundred and one, the rounding edge. A second test checks that a negative subtotal is refused with an illegal argument exception. You built this kind of project in the Maven episode and lab four.
@ParameterizedTest
@CsvSource({"4999, 0",
"5000, 500", "5004, 500",
"5005, 501"})
void save10(long sub, long exp) {
assertEquals(exp,
Pricing.discount(sub));
}
@Test void negativeRefused() {
assertThrows(IllegalArgument
Exception.class, () -> ...); } pytest
The same tests in pytest. A test is any function whose name starts with test, in a file whose name starts with test. Assertions are the plain Python assert statement, and pytest rewrites them to show both values when they fail. Parametrize gives the same four rows. pytest dash q runs everything quietly. Run against the real discount function, the four rows plus a type check report five passed in about ten milliseconds.
import pytest
from pricing import discount
@pytest.mark.parametrize(
"subtotal, expected", [
(4999, 0), (5000, 500),
(5004, 500), (5005, 501)])
def test_save10(subtotal, expected):
assert discount(subtotal) == \
expected
# pytest -q → 5 passed Side by side
Side by side, the two frameworks are the same ideas with different spelling. At test becomes a function named test something. Assert equals becomes a plain assert. Assert throws becomes pytest dot raises used in a with block. Parameterized tests become the parametrize mark. Before each becomes a fixture. Disabled becomes skip with a reason. And m v n test becomes pytest dash q. Learn one well, and the other takes an afternoon.
@Test def test_x():
assertEquals(a,b) assert b == a
assertThrows pytest.raises
@ParameterizedTest
@pytest.mark
.parametrize
@BeforeEach @pytest.fixture
@Disabled("why") @pytest.mark
.skip(reason=)
mvn test pytest -q A real failure
Plant ShopRung's rounding bug: drop the plus fifty, so the discount always rounds down. Run pytest. One row fails: assert five hundred equals five hundred and one, where five hundred is discount of fifty oh five. The test id in square brackets names the exact row. Four rows still pass, including fifty dollars itself. This is why the rounding edge row exists: without it, the bug ships. Always see a test fail like this once.
# bug: (subtotal * 10) // 100
> assert discount(subtotal) ==
expected
E assert 500 == 501
E + where 500 =
discount(5005)
FAILED test_pricing.py::
test_save10[5005-501]
1 failed, 4 passed Fixtures
Tests often need the same setup, like a fresh empty cart. JUnit uses before each, which creates the cart before every test. pytest uses fixtures: a function marked as a fixture returns the cart, and any test that names it as a parameter receives a fresh one. Fixtures can also clean up after the test with yield. The key is fresh: each test gets its own object, so no test leaves a mess for the next.
// JUnit
@BeforeEach void newCart() {
cart = new Cart(); }
# pytest
@pytest.fixture
def cart():
return Cart()
def test_add(cart):
cart.add("MG-201", 2)
assert cart.count() == 2 What to test
What should unit tests cover? Each rule's partitions and boundaries, the error paths with their exceptions and messages, and edge values like zero, empty, the maximum and rounding halves. What should they skip? Private helper methods, simple getters and the framework's own code. Test behaviour through the public interface, what the code does, not how it does it, so tests survive refactoring instead of breaking every time the code is tidied.
- each rule's partitions and boundaries
- error paths: bad input, exceptions and messages
- edge values: 0, empty, max, rounding halves
- not: private helpers, getters, framework code
- test what, not how
Common mistakes
Unit tests that look busy but catch little. Tests with no assertion at all. Asserting whatever the code currently returns, instead of what the requirement says. One test checking ten behaviours. Tests that only pass in a certain order. Using the real clock or random values. Testing private methods directly. And copying the production formula into the test to compute the expected value, so both share the same bug. Write expected values by hand.
- tests with no assertion
- asserting what the code does, not what it should
- one test, ten behaviours
- tests that depend on order
- real clock or random values
- testing private methods
- copying the production formula into the test
Say it like this
In the interview: a good unit test is fast, isolated, repeatable and self checking, with one reason to fail. It tests behaviour through the public interface with hand written expected values, covers boundaries and error paths, and I make sure it actually fails when the code is wrong. Then add that the framework matters less than the habits: JUnit five or pytest, the ideas are the same.
- "Fast, isolated, repeatable, self-checking, with one reason to fail. It tests
- behaviour through the public
- API with hand-written expected
- values, covers boundaries and error paths, and I make sure
- it fails when the code is wrong. JUnit 5 or pytest, the ideas are the same."