This article was originally published on my personal blog
The purpose of a unit test is to confirm the intended behavior of a small piece of code separated from other parts of your application.
But if you're just stepping into the world of testing automation, you may find yourself staring at a function with a blank expression on your face while you wonder what needs to be tested in that block of code.
This writers-block equivalent is one of the most difficult and frustrating hurdles to overcome for many unit testing newcomers. Developers are often forced to sink or swim and are left without resources to help them bridge the knowledge gap.
I was taught to look at functions through the lens of a gumball machine metaphor, providing a nearly instantaneous method to craft a testing outline.
But how does this metaphor help determine what needs to be supported by unit tests?
Let's take a look.
How does a gumball machine work? There are three major events:
- Put a quarter in the machine
- Turn the handle
- A gumball comes rolling out
Think of functions as a gumball machine and follow the three steps:
- Put the quarter in the machine (pass arguments to the function, if necessary)
- Turn the handle (execute the code under test — the function itself)
- A gumball comes rolling out (verify the behavior - the function returns the expected data)
It can't be that easy, right? Honestly, it should be! Unfortunately, though, it isn't uncommon to find legacy code that proves to be untestable. By pairing unit tests along with your code, you're forced to create an implementation that is easily testable (give Test Driven Development a try!). I won't go into this further; that's another article to write on a different day.
Obviously, some functions are more intricate than others - I find it's helpful to scan the function and write down the various logic branches and the possible values that can be returned. These notes become an outline for writing unit tests for that function.
While return values of functions help us determine test cases, it may also be worth writing tests the verify that a function calls another piece of code.
Remember, the purpose of a unit test is to confirm the intended behavior of a small piece of code separated from other parts of your application. Everything funnels down to the final step of the formula - given some input, what output does the function return? If it returns the intended values, the test passes. If not, something is wrong.
Try putting the Gumball Machine into practice and see if it assists you in creating an outline for your unit test cases. I've found this method to be very helpful - and make sure you pass this along and teach others who you may find with that familiar blank expression on their faces.
Gumball photo by Matt Birchler