simple testable code
Post on 20-Aug-2015
1.480 Views
Preview:
TRANSCRIPT
what and how
TDD is very similar to getting things done with small children around. I just ask myself, "Now what was I trying to do?" every 5 minutes.
@carinmeier
core values
simplicity over flexibility
concreteness over abstraction
soft-coupled tests over full code coverage
test aware dev over test first dev
simple code
Aesthetic simplicity
• clean
• formatted
Cognitive simplicity
• clear concepts
• logically organized
• No unecessaryindirection
• small state space
simple code
values are simpler than objectdata structures are simpler than classes
stateless is simpler than stateful
• Clean Code: A Handbook of Agile Software Craftsmanship, Robert C. Martin
• Simple Made Easy, Rich Hickey, http://www.infoq.com/presentations/Simple-Made-Easy
• The Master, The Expert, The Programmer, Zed Shaw, http://zedshaw.com/essays/master_and_expert.html
references
all about dependencies
The key to write testable code is to inject some of the class dependencies via constructor, method parameters (or setter methods).
In the test code, test objects are passed to the class under test.
static dependencies
Example: MessageSender.java
The problem is not to depend on concrete classes, but to have static dependencies.
The new operator is static.
use the right test object
dynamic mock: Provided by unit test libraries such as Mockito. Simple to use and limit the amount of test code to a minimum.
production code: Add dependencies to the production code. Easier with behavior-less classes such as data holder.
hand coded mock: May be needed if behavior to mock is complex. Can be really painful to maintain.
assert behavior not implementation
• Testing implementation makes the test code fragile
• Verify return values and mandatory side effects
• Avoid asserting more than needed• One assert per test?
stateless
Example: Statefull/StatelessProcessor.java
Stateless classes have no state space.
Stateless classes have do not worry about multithreading.
Stateless classes are simpler to setup for test.
top related