TDD, which is short for Test-Driven Development, is a way of developing your code logic tests first.
Benefits of Test-Driven Development
This leads to more stable code and can also help you with planning out your code:
Incremental Testing
You can run your test suite whenever you make changes to ensure everything works as expected.
Plan Through Errors
Building your code logic through the eyes of how it might fail can work similarly to pseudocode in helping you plan your code.
How to Write TDD
However, approaching a code project using TDD doesn't mean that you first write all the tests and then write a complex program. Doing this would most likely be quite complicated and premature optimization:
Image source: https://xkcd.com/974
Instead, you'll write a test for a specific function you are about to build. Right after writing the test, you build the function. Then, you can run your test suite, check whether it's all working as you expected, and then keep moving forward with the next test and function.
A Different Approach
Building your apps following test-driven development requires a different approach to coding. Initially, this approach might not seem intuitive, but it's worth practicing this skill. Especially when your applications become larger, it's crucial to have a good test suite up and running to avoid crashing everything and not knowing where the errors came from.
Refactoring your web scraper script to compartmentalize the different pieces into separate functions is a great way to practice TDD. You'll start by picking one idea of what you could test from that script, writing the test, and watching it fail when you run your test suite.
Then, you'll go into your production code file and refactor the functionality in there until the test you wrote earlier passes. Once you've got one happy dot (.) sitting in your unittest output message, you're ready to move on to write the next test that will initially fail until you've refactored your web scraper script as well.
In the next lesson, you'll start building your first test case for your web scraper script.
Check out the links below for a selection of good intros and resources that can help you get started working with a TDD approach.
Additional Resources
- Wikipedia: Test-Driven-Development
- FreeCodeCamp: Intro to TDD with Python
- Harry J.W. Percival: Obey the Testing Goat!
- Python 3 Patterns, Recipes and Idioms: Unit Testing & Test-Driven Development
Summary: What is TDD
- Test-driven development means approaching your code logic tests first
- Write test cases that help plan out the functionality of your production code
- Build the corresponding function in your code that'll make your test pass
- The benefits of TDD are incremental testing and planning through errors