1.
TDD and Refactoring¶
1.1.
TOC¶
1.2.
TDD (Test-Driven Development)¶
TDD Concept
TDD is about driving development from tests, offering a more iterative approach.
1.2.1.
Steps¶
- Express intent in the form of a test
- Test the test by Running it and Seeing it Fail
- Create the Minimum code to meet the needs of the test
- Run it and see it Pass
- Now in a stable, passing state, Refactor test and code for quality and generality
- Repeat
1.2.2.
Attributes of Good Code¶
- Modular
- Loosely Coupled
- Cohesive
- Separation of Concerns
- Information Hiding
1.2.3.
Two Important Classes of Test:¶
- Technical Testing
- User-Centered Testing
1.2.4.
Properties of Good Tests:¶
- Behavioral Focus
- Executable Specifications
- Control the Variables
- Repeatable and Reliable
1.2.5.
Common Testing Anti-pattern: Excessive Setup¶
Causes and Problems
- Cause: Poor Separation of Concerns in System under Test (SUT)
- Problems:
- Test and SUT are tightly-coupled and so Fragile
- Result is inflexible
- Hard to Understand and Debug
Corrections
- Improve Separation of Concerns in SUT
- Improve Abstraction in SUT
- Write Tests First!
1.2.6.
In TDD¶
- Focus on Interface Design
- Test Behavior Not Implementation
- Use Collaborators as Points of Measurements
- Inject Fake points of measurement with dependency injection
1.3.
Refactoring Legacy Code¶
1.3.1.
Approval Testing¶
Like snapshot testing, where the test compares function output with a previously saved snapshot of a function output every time the code is run.
1.3.2.
Steps¶
- Reduce Clutter
- Remove unnecessary comments and make variable names more informative
- Remove dead code
- Reduce Cyclomatic complexity (reduce number of branches)
- Extract a method
- Separate concerns
- Compose Methods
- Organize in a way using labels and names to make it easy to understand what the method does
Key Principle
"Move stuff that's related closer together Move stuff that's unrelated further apart"
Writing Test Names
When writing tests, it can help to think of the name for the test by starting it with 'should'