DEV Community

Discussion on: Explain Unit Testing like I'm five

Collapse
 
bertilmuth profile image
Bertil Muth

You think that your sister's china doll, that you hate so much, breaks when you drop it on the floor?

How would you find out if that is really case?

You would probably:

  1. Get the doll from your sister's room
  2. Drop it on the floor
  3. Compare what you expected (the doll breaks) to what has actually happened (the doll is ok, your foot hurts).

Step 1 is called "Arrange", because you prepare the test.
Step 2 is called "Act", because you do the actual test.
Step 3 is called "Assert", because you check if you were right.

In programming, the programmer just writes the story, as I have it explained to you, but in a language the computer understands. It's the computer that actually does the 3 steps. That's why these tests are called "automated tests".

If what actually happened in step 3 is what you expected to happen, we programmers say "the test passed". Otherwise, "the test failed".
So did the test with the china doll pass or fail? Right, it failed. Because it did not break.

We call these particular tests "unit tests", because we test a single thing. Most of the time something that is small. Like your sister's doll. And there's a lot more to break aeh test.

Collapse
 
cjbrooks12 profile image
Casey Brooks

Continuing with this analogy, I'll introduce mocking and its importance.

So you're pretty confident that the doll will not survive a drop onto your sister's floor, and you really want to test this. The problem is that your sister has friends over and her door is locked, so you can't actually go in there to test it. But you did already manage to steal the doll.

You know her room has wooden floors, but is usually covered in clothes. So you go to your room (which you normally keep very clean) and start throwing some clothes around. This way, you can test drop it in your room knowing that it would have the same effect as if you were to drop it in hers.

But this gets you thinking. Instead of throwing clothes on your floor, what would happen if you threw pillows around? Or dropped it onto carpet or tile instead. So you set up a series of situations where you drop the doll onto floors of these different types, but you do it in a very controlled manner so you know the only thing that changed from one test to the next is the floor.