- Part 1: Why use it?
- Part 2: Write My Tests First?
- Part 3: Keys to Effective TDD
- Part 3, Key #1: Write Testable Code
- Part 3, Key #2: Write Good Tests
- Part 3, Key #3: Using Fakes and Dependency Injection
- Part 4: Conclusion
Your Tests Should Be Readable
Your tests are code too, and just like all of your other code you want it to be nice and readable. This means naming your classes, functions and variables with meaning!
InvoicePrinterTests is a good name for a class that tests the InvoicePrinter class. TestClass1 is not.
PrintInvoice_Calls_Repository_FetchOrder() is a good name for a test that verifies that the OrderRepository.FetchOrder() method is called when we call PrintInvoice(). Test1() is not.
I like to name my test functions so they read like English, and if you were to replace the underscores with spaces, you’d have a pretty understandable statement (“PrintInvoice calls repository FetchOrder”). If you don’t like underscores, that’s fine – just choose a convention that helps you describe exactly what the function is testing.
Your Tests Should Be Maintainable
Just like with “regular” code, we want our tests to be maintainable. This means your test functions should probably be no more than 10-15 lines in length.
And another thing I’ve discovered: if you run into a situation where you’re finding it hard to test something, or your test is just getting big and complicated – you almost certainly need to refactor something. I’ve run into this many times and every time I found that it was because the code I was trying to test was too complicated and needed to be split up and tested separately.
Your Tests Should Test Only One Thing
Each test function should test one, and only one, thing. A good check (although this isn’t always true) is to see whether you have more than one Assert statement. If so, there’s a good chance that you are testing more than one thing.
Your Tests Should Be Trustworthy
In order for tests to have long lasting value, you have to trust them. If you’re not confident in your tests, then you can’t be confident in the results they produce. If, on the other hand, you are totally confident in your tests, when they fail you can be sure that there is a bug in your code that needs to get squashed.
How do you make “trustworthy” tests? If you follow the 3 guidelines above, you’ll be well upon your way.