The Clean Code Talks – Unit Testing
Writing testable code is more important than writing good tests
If the code is difficult to overwrite, then it will be difficult to test
- Main method in procedural program or static method in object oriented code is difficult to test
- The dependency in main program cannot be mock
- Deep inheritance
- The parent class cannot be mock, need to test all inheritance
Purely procedural is hard to test, because it is difficult to isolate the logic. Procedual code difficult to overwrite.
E.g main method is difficult to test
- The parent class cannot be mock, need to test all inheritance
- Main method in procedural program or static method in object oriented code is difficult to test
Unit test should be done by the same developer
- Test engineer is difficult to write good test on untestable code
- Developer cannot get feedback on untestable code if they don’t write tests
- Writing testable code > writing good test
Different test level
- Scenario test
- Simulate what user does
- Whole system is involved in every tests.
- Pros:
- It test exactly how user use the system
- High coverage with few tests, as whole system is involved
- Cons:
- Don’t know which part is buggy when test failed
- Difficult to reproduce failures
- Difficult to get corner case
- Functional test
- Test a sub-system with simulators for external dependecies
- Focus on class-interaction
- Pros:
- Tests are short enough to run before developers submit code
- Can simulate condition not possible in scenario tests
- Cons:
- Still need debugger to figure what went wrong
- Unit tests
- All this levels are important. *
- Unit Test is for finding bugs, not for proving it works *
Dependnecy injection
- Dependency create a seam between classes and it depending classes, so we can replace the dependency with mock object ro trusted (tested) object easily.
- Test driver should set up and control all components in the object graph.
Some tips
new()
is static and causes direct binding, don’t put logic in it- Get depending object in constuctor only
PS: Polymorphism: 一個訊息嘅意義由接收者去解釋,唔係由發出者去決定。換上唔同嘅接收者,就可以改變system behaviour。有polymorphism,就可以換一D mock object做testing