TDD
Test-driven development is a short, repetitive process.
- Write a failing test case for an enhancement (red)
- Implement the minimum code to pass the test (green)
- Refactor the code to meet project standards (refactor)
Benefits
- Focus on requirements
- Short development cycles
- Safety net for refactoring
- Forces thoughts about design
Use Cases
- Maximizing test coverage
- Supporting continuous integration
- Improving legacy code
BDD
Behavior-driven development builds on TDD.
- Specify desired behavior in a consistent format
- Write a failing test case for a scenario
- Implement the minimum code to pass the test
- Refactor the code to meet standards
Use Cases
- Outlining required tests
- Communicating with stakeholders
- Documenting design decisions
But what is a consistent format?
One Format: Gherkin
- Domain specific language
- Business readable
- From Cucumber BDD (Ruby)
- Documents behavior
- Binds to test cases
Example: Gherkin
Feature: App store validates customer credit card
Scenario: First-time customer
Given a customer is unknown
When the customer checks out
Then the checkout process should prompt for cc info
Secnario: Customer credit card expired
Given a customer is known
And the cc on-file is expired
When the customer checks out
Then the checkout process should prompt for new cc info
...
Behave
"behave is behaviour-driven development, Python style. ... [It] uses tests written in a natural language style, backed up by Python code."
- pythonhosted.org/behave
Components
- Feature files contain Gherkin scenarios
- Step files contain test code
- behave CLI binds the two
Demo: Fibonacci Numbers
Spec, test, code, refactor
What about non-trivial units?
Say I have a class that uses a database?
Dependency Injection
- Make components pluggable
- In production, use real objects (e.g., database)
- In test, use "fakes" (e.g., stub database)
To Be Continued
We'll need a whole other session
Example: Mocha
describe('app store validation', function(){
describe('first-time customer', function() {
// test setup
it('should prompt for cc info', function() {
// test assertions
});
});
});
Review
- TDD and BDD
- Gherkin
- Behave
- Features and steps
- Mocha