Software Craftsmanship
Test Driven Development
November 8, 2016
Test-Driven Development
- Write a failing unit test.
- Write the minimum amount of code to make the test pass.
- Refactor the new code to acceptable standards without breaking the test.
Requirements must be completely understood through use cases and user stories.
- "Keep it simple, stupid"
- "You aren't gonna need it"
TDD Benefits
- TDD means writing more tests, and programmers who write more tests are more productive.
- Beyond standard unit testing, TDD also drives the design of the application, allowing developers to consider how the API will be used by clients and to write against the interface instead of the implementation (DIP).
- Resulting code tends to be more modular because developers think in terms of smaller, testable units of code as they only write code to pass a testable unit. Using mock objects also helps contribute to modularity because it requires swapping out modules.
Unit Testing Conventions
Test structure
- Setup
- Execution
- Validation
- Clean up
- Treat your test code with the same respect as your production code.
- Separate common set up and clean up logic.
- Work with your team to review your tests and test practices.
Avoid
- unnecessary or useless tests
- depending on external environments
- depending on system state manipulated by previously executed test cases
- dependencies between test cases
- testing execution timing or performance
@Before
public void setUp() {
bill = new Bill(2, new Server("gtb012", "Reid"));
calculator = new BillCalculator(.05);
}
@After
public void tearDown() {
bill = null;
calculator = null;
}
@Test
public void testCalculateTax() {
bill.addItem(new Item("milk", 1.23));
bill.addItem(new Item("cereal", 2.13));
double tax = calculator.calculateTax(bill);
assertEquals(0.17, tax);
}Unit Test Mocking
Mock objects can simulate the behavior of complex, real objects when the real object is impractical or impossible to incorporate in a unit test.
Creating a mock object will stub the method implementations.
Usage of a mock object by the unit under test (UUT) allows control and verification of the invocation of the mock by the UUT.
Software Craftsmanship - Test Driven Development
By cof_softwarecraftsmanship
Software Craftsmanship - Test Driven Development
2016 - Day 2.3
- 453