3 ms·
When you're writing your procedures, you have to think about what you want them to do. What small unit of work each procedure should perform. That's the best
by tejohnso 12y ago
When you're writing your procedures, you have to think about what you want them to do. What small unit of work each procedure should perform. That's the best time to write the tests for the procedure, because it will help you to think of edge cases that you might otherwise miss, and it will confirm that the procedure does what you expect before you move onto the next. It's also the easiest time to write the test for the procedure, because you haven't yet committed to any particular level of complexity or dependency structure. If you write tests first, your code will always be testable. If you attempt to show up the next day and start writing tests, you may find that the person who wrote the code yesterday wrote some pretty untestable code. Another benefit to having the tests is that they will continue to pay off as you modify the code weeks and months later, always confirming that you haven't broken anything.
Like most other learning endeavours, I found that the best approach was to start small. Try something simple like a fizz-buzz test. You'll probably have more trouble setting up and writing the tests than writing the code under test. That's okay. Like any other learning process, it takes time to get used to the new language and behaviour that is required to become fluent in writing testable code. Make sure that every time you save your working code, your tests run and you can see the result so that you get immediate feedback. And make sure to always work in as small a unit of work as seems comfortable.
Here are some example test function names for fizzbuzz
1. itPrintsFizzForMultiplesOfThree()
2. itPrintsBuzzForMultiplesOfFive()
These tests might be too broad in scope. Where is it getting the numbers that it's checking for multiples? What does "print" mean? How are the tests going to confirm what was printed?
1. itReturnsTrueForMultiplesOfThree()
2. itReturnsTrueForMultiplesOfFive()
3. itReturnsEitherFizzOrBuzzOrTheNumber()
4. itSendsTheResultToOutput()
These tests are against simpler methods and are easier to write but the tradeoff is that they make the code under test too fine grained at times. Can you have too many tests? I don't think that's likely in practice, not if they're true unit tests and extremely quick to execute. But some would disagree when they see a five method fizzbuzz class rather than a class with one "doTheWholeThing" method. You have to find what works for you. When you return to your code a day or two later, do the tests immediately make sense? If not, they're probably too complicated. Start small, get a feel for the shift in mindset, grow from there.