What do we want tests to do for us?
Before we start learning about test-driven development, what it is, and what the process involves, let’s step back and think about what we want. Without knowing all the details about what a test is, let’s ask ourselves what our tests should look like.
I like to relate programming concepts to everyday experiences whenever possible. Maybe you have an idea to solve a problem that you have noticed and want to see whether your idea will work. If you wanted to test this idea before announcing it to the world, how would you do it?
You probably won’t be able to test everything to do with your idea at once. What would that even mean? There are probably small parts of your idea that you can think about initially. These should be easier to test and should help to clarify your idea and get you to think of other things to test.
So, let’s focus on simply testing small parts of the idea, whatever it is. You’d want to get everything set up and then start some actions or steps that should tell you whether each part works or not. Some of your tests might work well and some might cause you to rethink your idea. This is definitely better than jumping into the full idea without knowing whether it will work or not.
To put this into a real context, let’s say you have an idea to build a better broom. That’s a vague idea that’s hard to envision. However, let’s say that while sweeping the floor recently, you noticed your arms getting sore and thought that there had to be a better way. Thinking about the actual problem is a good way to turn a vague idea into something with a more solid meaning.
Now, you might start thinking about testing broom handles of different shapes, different grips, or different sweeping motions. These are the smaller parts of the idea that can be tested. You can take each grip or motion and turn it into a set of steps or actions that will test that part until you find one that works best.
Well, in programming, a set of steps can be a function. It doesn’t matter what that function does right now. We can think of each test as represented by a function. If you can call a function and it gives you the expected result, then you can say that the test passed. We’ll build on this idea throughout this book.
Now that we’ve decided to use a function for a test, what should it look like? After all, there are lots of ways to write a function.