- Write tests before you write code
- Tests drive the code structure
Kent Beck
The original description of TDD was in an ancient book about programming.
Kent Beck
It said you take the input tape, manually type in the output tape you expect, then program until the actual output tape matches the expected output.
https://i.imgur.com/RwLbz9n.png
https://i.imgur.com/RxCSYUI.png
David Heinemeier Hansson
I don't know how/what to test before I've seen the program.
Kent Beck
I have no business programming something before I know how to test it.
https://jfiaffe.files.wordpress.com/2014/09/redgreenrefacor.png
- Write a failing test
- Make the test pass
- Clean-up code
- Repeat until desired logic
[Fact]
public void TestMyStack()
{
var example = new Example();
var result = example.Add(1);
Assert.Equal(1, result);
}
class Example
{
public int Store = 0;
internal int Add(int i)
{
throw new NotImplementedException();
}
}
Fail!
class Example
{
public int Store = 0;
internal int Add(int i)
{
Store = Store + i;
return Store;
}
}
Pass!
class Example
{
public int Store = 0;
internal bool Add(int i)
{
return Store + i; // inline
}
}
Refactor!
- Tests are already created
- Drives great architecture
- Easier to change
- Lets you known when you are "done"
-
Tests and code are only as good as what the developer anticipates
-
Changes to the code require more changes to the unit tests
-
Longer time spent on single feature
But like anything, this improves with practice
https://wallpapercave.com/wp/hN0TnNU.jpg
Michal Feathers
Legacy Code is Code Without Tests
https://i.imgur.com/1HqD70B.png
https://i.imgur.com/WVQ8QAB.png
https://i.imgur.com/hBHGqc8.png
- Tests drive loose coupling
- Write tests you'd expect to pass
- Break up code using "safe refactors"
- Get your classes out of tight dependencies
BDD focuses on tests which describe behavior. Rather than single units of code.
Feature: search Wikipedia
Scenario: direct search article
Given Enter search term 'Cucumber'
When Do search
Then Single result is shown for 'Cucumber'
- Test Driven Development
- Red Green Refactor
- Better, more changable code
- Trade-off in time spent developing
- Great for greenfield AND legacy code!
- Aim for loosely-coupled code
- Avoid heavy mocking!
- Look at BDD for a TDD approach to E2E