Testing and design quality
Introducido
5:16
Programación orientada a objetos
This course is about how a small script grows into a system that other people can safely change. The first two units build the object: classes, references and…
Narración en inglés · subtítulos en inglés y 中文 que puedes cambiar
En esta lección
| English | Significado |
|---|---|
| test suite | |
| test/test/ | |
| refactoring/rɪˈfæktərɪŋ/ | refactorización |
| unit test/ˈjuːnɪt test/ | prueba unitaria |
| arrange/əˈreɪndʒ/ | organizar |
| act/ækt/ | actuar |
| assert/əˈsɜːt/ | assertar |
| boundary test/ˈbaʊndəri test/ | A test using values at, just inside or just outside the limits of an allowed input range. |
| Coverage/ˈkʌvərɪdʒ/ | |
| single responsibility principle/ˈsɪŋɡl rɪˌspɒnsəˈbɪlɪti ˈprɪnsɪpl/ | principio de responsabilidad única |
| coupling/ˈkʌplɪŋ/ | acoplamiento |
| cohesion/kəʊˈhiːʒn/ | cohesión |
Did the change break anything?
- You move the fine calculation out of
Loaninto its own class. The program still starts, but is every result still the same? - Clicking around proves very little. A good test suite 测试套件 answers in one second, and this lesson shows how to write one.
Tests pin behaviour
- Refactoring 重构 changes structure without changing behaviour. It is only safe when the behaviour is pinned down.
- Unit tests 单元测试 are those pins: each one checks one promise the code makes.
Arrange, act, assert
- One test, one behaviour: arrange 准备 the objects, act 执行 with one call, assert 断言 the outcome the caller can see.
def test_renew_ok():
loan = Loan(20) # arrange
out = renew(loan, 7) # act
assert out == 27 # assert
Put the parts of a unit test in order.
Dificultad 3/5 · 200 monedas + un pequeño bono en el primer intento de hoy
Arrange, act, assert — one behaviour per test.
Behaviours, not methods
- Name tests after behaviours: "renew past the limit raises" is a behaviour;
test_daysis just a method name. - A behaviour test survives renames and fails exactly when a promise changes. Assert 断言 what callers see, not private fields.
A good unit test is named after —
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
Behaviour names survive renames and fail exactly when a promised outcome changes.
A test that asserts the private field loan._days is a good behaviour test.
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
It pins storage, not a promise, so it breaks on refactors. Assert what the caller sees, such as the returned days.
Test the boundary
renewallows up to 30 days, because the check is> 30. Test three points: inside (20 + 7 = 27), exactly on the limit (20 + 10 = 30, allowed) and past it (20 + 11 raises, loan unchanged).- The boundary test 边界测试 catches the classic slip of writing
>=for>.
import pytest
def test_renew_on_limit():
loan = Loan(20)
assert renew(loan, 10) == 30
def test_renew_past_limit_raises():
loan = Loan(20)
with pytest.raises(ValueError):
renew(loan, 11)
assert loan.days == 20
pytest.raisespasses only if the call raises that error. The last line checks the second promise: a failed renewal changes nothing.
The rule is "raise if days + extra > 30". What does renew(Loan(20), 10) return?
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
20 + 10 = 30 is not more than 30, so the renewal is allowed.
The coverage grid
- List behaviours down the side and tests across the top. Each filled cell is a behaviour a test pins.
- An empty row is the next test to write. Coverage 覆盖率 follows the list of promises, not the lines of code.

An empty row in the coverage grid means —
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
Rows are behaviours, columns are tests: an empty row is the next test to write.
Match each test to the behaviour it pins.
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
One behaviour per test; the grid's empty row is the next one to write.
Refactor under green
- Move fines into a
FineCalculatorclass (the single responsibility principle 单一职责原则: one reason to change), and the renew tests still pass untouched. - Coupling 耦合 (how much classes depend on each other) went down; cohesion 内聚 (one purpose per class) went up. That is the direction of every good change.
Moving fine calculation into FineCalculator is safe when —
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
Green tests provide evidence that the tested behaviours still work, but cannot prove that all behaviour is unchanged.
Worked example: one bug, one red test
- The three renew tests 测试 run and print
3 passed. - Someone changes the check to
>= 30. Nowtest_renew_boundaryfails and the other two pass: one red test names the exact broken promise.
The check is wrongly changed to days + extra >= 30. How many of the three renew tests fail?
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
Only the boundary test (20 + 10 = 30) changes outcome. 27 still passes and 31 still raises.
Three common slips
- Asserting private internals. Every refactor then breaks the test 测试.
- Sharing changeable state between tests. Test B passes only if test A ran first.
- Chasing line coverage on getters while the limit branch has no test.
Recap
- Arrange, act, assert: one behaviour per test, named after the behaviour.
- Test inside, on and past every boundary; the grid shows the next test to write. For
renew, limit 30 days:
| Test | Loan days | Expected |
|---|---|---|
| Inside | 27 | allowed |
| On the limit | 30 | allowed |
| Past it | 31 | raises; loan unchanged |
- Green tests make refactoring 重构 safe; aim for low coupling and high cohesion.
¿Qué salió mal? Solo el equipo del sitio ve esta información.