TDD Revisited Jon Limjap
MVP for Visual C#
What is TDD?
Using unit tests to design software Allows change in code without fear of changing functionality Produces loosely coupled objects and methods with single responsibilities Unit tests are just side effects: main point is DESIGN
What is TDD not?
Substitute for QA testing
Necessarily means successful project
Silver bullet
Mindset
Red
New code
Write test before implementing class Internal workings of classes and methods should not matter
Existing code
Write test to reproduce bug
Green
Write least possible code to pass all tests
Take shortcuts if necessary
Refactor!
Applies to both implementation code and test code Change code without changing functionality (ergo, without introducing bugs) Remove implementation shortcuts – make sure software design is sound/follows tenets of OOP Optimize for design/performance/maintainability
Rinse and repeat
Writing tests
Think about how you want to express your code and intentions Think about inputs, and intended output Separate small, isolated areas of functionality
Arrange, Act, Assert
Arrange all necessary preconditions and inputs Act on the object or method under test Assert that the expected results have occurred
How to test in isolation?
Stubs
Method returns a specified result, e.g., property getter returns a constant value
Mocks
Asserting that a certain method has been called within a test Test checks for the method call, not the result, but some tests check for both
What about the DB?
Integration tests
Make sure everything works together Also applies to the file system, web services, etc., ergo, everything that can fail without you knowing
Integration testing sucks because...
Fragile Tests
Depends on state of external system Breakage cause lost confidence on tests – even if it's not the tests' fault
Usually leaves artifacts behind (files, orphaned DB data)
Demo AAA, Stubs, Mocks, & integration testing using MbUnit and Rhino Mocks 3.5