Designing for Testability
In this pack:
sizing,
notation,
rule strictness.
Overview
A test that is awkward to write is telling you something about the
design. When a test must build a working database, start a thread or
fix the machine's clock before it can check one rule, the object under
test has taken on work that belongs at its edge. This skill changes the
design so a test can choose every value it cannot repeat, reach every
collaborator through a port, and check only what a caller can see. A
test written this way repeats on every machine and does not care which
day it runs.
When to use
- A test gives a different result on a different day, or after a
restart, because something inside reads the time, draws a random
value, generates an identifier or reads a setting.
- A test must build, start or reset many things to check one rule.
- A constructor reads a file, opens a connection or starts a thread.
- Code reaches a collaborator through a static call, a global or a
class's single instance.
- One method both decides something and talks to a slow or effectful
collaborator.
- A field, getter, flag or method exists only so a test can reach
inside.
- You are choosing whether a collaborator needs a port, or whether a
value can be passed as it is.
When not to use
- The question is how to write or name a test, or which kind of
stand-in to pass: that is
testing object-oriented code.
- The code has no tests and must change now, before its design can
improve: getting a test around today's code is in
working with legacy code.
- A screen, a scheduled job or a message listener cannot run without
its framework: layering the system
rule 4 keeps that edge humble.
- The dependency is a value or a library with no effects, such as date
arithmetic, which a test can use as it is.
Core rules
Rule. Treat a test that is hard to write as a finding about the
design: name what the test must build, start or reset before it can
check one rule, and change the design that makes that work necessary,
not the test. The index's red flag, a test that needs many mocks to
check one decision, is the usual sign.
Rule. Receive every source of a value a test cannot repeat through
a port passed into the constructor, and never ask the machine for it
inside the object: the current time, a random draw, a newly generated
identifier, a setting read from the environment. These are outside
systems like any other, as
inverting dependencies rules
1 and 2 ask. A test then passes a stand-in, an object it puts in a
real collaborator's place, that answers the value it chose.
Default. Pass the value, not its source, to a domain object that
needs only the value: an aggregate's method takes the time as a
parameter, as
modeling lifecycles rule 5
gives recordNoShow(now), and the use-case object asks the port once
and passes the answer on. The exception is an object that must ask
again while it handles one message, such as a long run that checks
the time between items: it holds the port.
Rule. Let a constructor set the object's fields, check its
arguments and build the parts the object owns, and nothing more: it
reads no file, opens no connection, starts no thread, sends nothing
to an outside system and builds no collaborator with new. What a
constructor may build and what it must receive is decided by
constructing valid objects
rule 6 and
inverting dependencies rule
2; this rule keeps work out of the constructor, because that work
runs in every test that builds the object.
Rule. Reach no collaborator that has effects or answers differently
from one call to the next through a static method, a global or a
class's single instance: one object the class keeps for every caller.
Keep static methods for named factories and for calculations that
use only their arguments. A static call cannot be replaced in a
test, and a single instance carries one test's state into the next.
Pass each collaborator in and build the single instance at the
composition root, as
inverting dependencies rules
2 and 3 ask.
Default. Split the decision from the effect: put the logic that
would otherwise need a slow or uncontrollable collaborator in an
object that takes plain values and answers plain values, and keep the
code that touches the collaborator so small that it needs no test of
its own. A humble object keeps only the code that needs the hard
edge and sends the rest inward; this is the humble object that
layering the system rule 4 asks
of each edge, used inside any class. The exception is code with
nothing to decide, such as a method that passes a value to its port.
Judgement. Add a seam for a test only where the collaborator is
slow, has effects or gives answers the test cannot choose, and use a
value, or a domain object that is fast and answers the same every
time, as it is. A seam is an interface where one implementation
can replace another without editing the code that uses it. A
collaborator that is awkward to control in a test is reason enough
for a port, as
inverting dependencies rule
6 says; a seam added for that reason has one adapter and the test's
stand-ins behind it, not a family of implementations. What tips the
balance is whether the test can make the collaborator give the answer
it needs without a seam.
Rule. Never open a production class only so a test can reach inside
it: add no public field, getter, flag or method that only tests
use. What a test needs to see is either an outcome the class
already offers its callers or a message it sends through a port.
When it is neither, the test is checking the inside, which
testing object-oriented code
rule 1 forbids.
Pattern
Before, OpenTreatmentCourse draws a course number with a static call
inside run. CourseNumber.random() is a static method taken to draw a
new random number on each call, so a test cannot choose the number run
answers, nor get the same one on a second run (rules 2 and 5).
Before:
class OpenTreatmentCourse
- courses: TreatmentCourses
+ new(courses: TreatmentCourses)
+ run(patient: PatientId): CourseNumber
number := CourseNumber.random()
courses.add(new TreatmentCourse(number, patient))
return number
After, the number arrives through a port the class receives, and a test
can choose it.
After:
interface CourseNumbers
+ next(): CourseNumber
class OpenTreatmentCourse
- courses: TreatmentCourses
- numbers: CourseNumbers
+ new(courses: TreatmentCourses, numbers: CourseNumbers)
+ run(patient: PatientId): CourseNumber
number := numbers.next()
courses.add(new TreatmentCourse(number, patient))
return number
class FixedCourseNumbers implements CourseNumbers
- number: CourseNumber
+ new(number: CourseNumber)
+ next(): CourseNumber
return number
TreatmentCourses is taken to be the courses' repository port, whose
add stores a new course once. new TreatmentCourse(number, patient)
is taken to build a course for the patient under that number, a class
this fence does not declare. CourseNumber is a value. The adapter
behind CourseNumbers in the program answers a new number on each call.
run answers the number because it is the identifier of something just
created, which
encapsulating state and behaviour
rule 4 allows. What is stored is one TreatmentCourse under its
CourseNumber, in the clinic's database, in the transaction the
use-case object opens and ends, as
placing domain logic rule 2 asks.
The test builds OpenTreatmentCourse with an in-memory
TreatmentCourses and a FixedCourseNumbers, sends run once, and
checks that the answer is the chosen number and that the store holds a
course under it. Each version stores one course and asks for one number
per run.
Red flags
Places to look, not verdicts. A red flag becomes a finding only with
evidence: a measurement, a reproducible bug, or a failing test.
- A test that must build, start or reset many things to check one rule.
- A domain class that asks the machine for the time, a random number or
a new identifier.
- A constructor that reads a file, opens a connection or starts a
thread.
- A static call to something that writes, sends or answers differently
each time.
- A field, getter or flag that only tests use.
- A decision and the effect it causes in one method that no test can
reach.
Common mistakes
- Fixing a hard test with more stand-ins instead of changing the design.
- Giving an aggregate a clock it asks once, instead of passing it the
time.
- A port for a value or a calculation with no effects.
- Moving work out of a constructor into a setup method callers must
remember.
- Keeping a test-only method because removing it breaks the test.
Related skills
Further reading
- Sources a test cannot repeat
- Splitting decisions from effects
1---2name: oo-designing-for-testability3description: Use when tests depend on today's date, random values or generated ids, when a constructor does real work, or code is made public only for tests.4license: MIT5metadata:6 source: https://skillmd.com/skills/yutna/oo-designing-for-testability7 version: 0.21.08 pack: object-oriented-design-skills9---1011# Designing for Testability1213**In this pack:**14[sizing](../oo-design/SKILL.md#how-much-design-a-task-warrants),15[notation](../oo-design/references/notation.md),16[rule strictness](../oo-design/SKILL.md#how-strictly-a-rule-is-meant).1718## Overview1920A test that is awkward to write is telling you something about the21design. When a test must build a working database, start a thread or22fix the machine's clock before it can check one rule, the object under23test has taken on work that belongs at its edge. This skill changes the24design so a test can choose every value it cannot repeat, reach every25collaborator through a port, and check only what a caller can see. A26test written this way repeats on every machine and does not care which27day it runs.2829## When to use3031- A test gives a different result on a different day, or after a32 restart, because something inside reads the time, draws a random33 value, generates an identifier or reads a setting.34- A test must build, start or reset many things to check one rule.35- A constructor reads a file, opens a connection or starts a thread.36- Code reaches a collaborator through a static call, a global or a37 class's single instance.38- One method both decides something and talks to a slow or effectful39 collaborator.40- A field, getter, flag or method exists only so a test can reach41 inside.42- You are choosing whether a collaborator needs a port, or whether a43 value can be passed as it is.4445## When not to use4647- The question is how to write or name a test, or which kind of48 stand-in to pass: that is49 [testing object-oriented code](../oo-testing-object-oriented-code/SKILL.md).50- The code has no tests and must change now, before its design can51 improve: getting a test around today's code is in52 [working with legacy code](../oo-working-with-legacy-code/SKILL.md).53- A screen, a scheduled job or a message listener cannot run without54 its framework: [layering the system](../oo-layering-the-system/SKILL.md)55 rule 4 keeps that edge humble.56- The dependency is a value or a library with no effects, such as date57 arithmetic, which a test can use as it is.5859## Core rules60611. Rule. **Treat a test that is hard to write as a finding about the62 design: name what the test must build, start or reset before it can63 check one rule, and change the design that makes that work necessary,64 not the test.** The index's red flag, a test that needs many mocks to65 check one decision, is the usual sign.66672. Rule. **Receive every source of a value a test cannot repeat through68 a port passed into the constructor, and never ask the machine for it69 inside the object: the current time, a random draw, a newly generated70 identifier, a setting read from the environment.** These are outside71 systems like any other, as72 [inverting dependencies](../oo-inverting-dependencies/SKILL.md) rules73 1 and 2 ask. A test then passes a stand-in, an object it puts in a74 real collaborator's place, that answers the value it chose.75763. Default. **Pass the value, not its source, to a domain object that77 needs only the value: an aggregate's method takes the time as a78 parameter, as79 [modeling lifecycles](../oo-modeling-lifecycles/SKILL.md) rule 580 gives `recordNoShow(now)`, and the use-case object asks the port once81 and passes the answer on.** The exception is an object that must ask82 again while it handles one message, such as a long run that checks83 the time between items: it holds the port.84854. Rule. **Let a constructor set the object's fields, check its86 arguments and build the parts the object owns, and nothing more: it87 reads no file, opens no connection, starts no thread, sends nothing88 to an outside system and builds no collaborator with `new`.** What a89 constructor may build and what it must receive is decided by90 [constructing valid objects](../oo-constructing-valid-objects/SKILL.md)91 rule 6 and92 [inverting dependencies](../oo-inverting-dependencies/SKILL.md) rule93 2; this rule keeps work out of the constructor, because that work94 runs in every test that builds the object.95965. Rule. **Reach no collaborator that has effects or answers differently97 from one call to the next through a static method, a global or a98 class's single instance: one object the class keeps for every caller.99 Keep static methods for named factories and for calculations that100 use only their arguments.** A static call cannot be replaced in a101 test, and a single instance carries one test's state into the next.102 Pass each collaborator in and build the single instance at the103 composition root, as104 [inverting dependencies](../oo-inverting-dependencies/SKILL.md) rules105 2 and 3 ask.1061076. Default. **Split the decision from the effect: put the logic that108 would otherwise need a slow or uncontrollable collaborator in an109 object that takes plain values and answers plain values, and keep the110 code that touches the collaborator so small that it needs no test of111 its own.** A humble object keeps only the code that needs the hard112 edge and sends the rest inward; this is the humble object that113 [layering the system](../oo-layering-the-system/SKILL.md) rule 4 asks114 of each edge, used inside any class. The exception is code with115 nothing to decide, such as a method that passes a value to its port.1161177. Judgement. **Add a seam for a test only where the collaborator is118 slow, has effects or gives answers the test cannot choose, and use a119 value, or a domain object that is fast and answers the same every120 time, as it is.** A seam is an interface where one implementation121 can replace another without editing the code that uses it. A122 collaborator that is awkward to control in a test is reason enough123 for a port, as124 [inverting dependencies](../oo-inverting-dependencies/SKILL.md) rule125 6 says; a seam added for that reason has one adapter and the test's126 stand-ins behind it, not a family of implementations. What tips the127 balance is whether the test can make the collaborator give the answer128 it needs without a seam.1291308. Rule. **Never open a production class only so a test can reach inside131 it: add no public field, getter, flag or method that only tests132 use.** What a test needs to see is either an outcome the class133 already offers its callers or a message it sends through a port.134 When it is neither, the test is checking the inside, which135 [testing object-oriented code](../oo-testing-object-oriented-code/SKILL.md)136 rule 1 forbids.137138## Pattern139140Before, `OpenTreatmentCourse` draws a course number with a static call141inside `run`. `CourseNumber.random()` is a static method taken to draw a142new random number on each call, so a test cannot choose the number `run`143answers, nor get the same one on a second run (rules 2 and 5).144145Before:146147```text148class OpenTreatmentCourse149 - courses: TreatmentCourses150 + new(courses: TreatmentCourses)151 + run(patient: PatientId): CourseNumber152 number := CourseNumber.random()153 courses.add(new TreatmentCourse(number, patient))154 return number155```156157After, the number arrives through a port the class receives, and a test158can choose it.159160After:161162```text163interface CourseNumbers164 + next(): CourseNumber165166class OpenTreatmentCourse167 - courses: TreatmentCourses168 - numbers: CourseNumbers169 + new(courses: TreatmentCourses, numbers: CourseNumbers)170 + run(patient: PatientId): CourseNumber171 number := numbers.next()172 courses.add(new TreatmentCourse(number, patient))173 return number174175class FixedCourseNumbers implements CourseNumbers176 - number: CourseNumber177 + new(number: CourseNumber)178 + next(): CourseNumber179 return number180```181182`TreatmentCourses` is taken to be the courses' repository port, whose183`add` stores a new course once. `new TreatmentCourse(number, patient)`184is taken to build a course for the patient under that number, a class185this fence does not declare. `CourseNumber` is a value. The adapter186behind `CourseNumbers` in the program answers a new number on each call.187188`run` answers the number because it is the identifier of something just189created, which190[encapsulating state and behaviour](../oo-encapsulating-state-and-behaviour/SKILL.md)191rule 4 allows. What is stored is one `TreatmentCourse` under its192`CourseNumber`, in the clinic's database, in the transaction the193use-case object opens and ends, as194[placing domain logic](../oo-placing-domain-logic/SKILL.md) rule 2 asks.195196The test builds `OpenTreatmentCourse` with an in-memory197`TreatmentCourses` and a `FixedCourseNumbers`, sends `run` once, and198checks that the answer is the chosen number and that the store holds a199course under it. Each version stores one course and asks for one number200per `run`.201202## Red flags203204Places to look, not verdicts. A red flag becomes a finding only with205evidence: a measurement, a reproducible bug, or a failing test.206207- A test that must build, start or reset many things to check one rule.208- A domain class that asks the machine for the time, a random number or209 a new identifier.210- A constructor that reads a file, opens a connection or starts a211 thread.212- A static call to something that writes, sends or answers differently213 each time.214- A field, getter or flag that only tests use.215- A decision and the effect it causes in one method that no test can216 reach.217218## Common mistakes219220- Fixing a hard test with more stand-ins instead of changing the design.221- Giving an aggregate a clock it asks once, instead of passing it the222 time.223- A port for a value or a calculation with no effects.224- Moving work out of a constructor into a setup method callers must225 remember.226- Keeping a test-only method because removing it breaks the test.227228## Related skills229230- [oo-design](../oo-design/SKILL.md) sizes a task and defines the rule231 labels.232- [oo-testing-object-oriented-code](../oo-testing-object-oriented-code/SKILL.md)233 writes and names the test this skill makes possible, and its rule 1234 forbids checking the inside.235- [oo-inverting-dependencies](../oo-inverting-dependencies/SKILL.md)236 puts a port beside the domain, passes collaborators in and builds the237 composition root, which rules 2, 4, 5 and 7 rely on.238- [oo-constructing-valid-objects](../oo-constructing-valid-objects/SKILL.md)239 keeps an object complete from its constructor and says which parts it240 builds, which rule 4 relies on.241- [oo-layering-the-system](../oo-layering-the-system/SKILL.md) keeps a242 hard edge humble, which rule 6 uses inside a class.243- [oo-modeling-lifecycles](../oo-modeling-lifecycles/SKILL.md) gives the244 time to a transition method, which rule 3 follows.245- [oo-working-with-legacy-code](../oo-working-with-legacy-code/SKILL.md)246 gets a test around today's code before its design can improve.247248## Further reading249250- [Sources a test cannot repeat](references/sources-a-test-cannot-repeat.md)251- [Splitting decisions from effects](references/splitting-decisions-from-effects.md)