Writing Good Unit Tests: A Step By Step Tutorial
Tags: unittesting, codequality, testing, problemsolving
Published: 2018-11-21 22:01:53

---
title: Writing Good Unit Tests: A Step By Step Tutorial
published: true
tags: unit testing, code quality, testing, problem solving
description: This is a tutorial to help you write comprehensive unit test suites.
canonical_url: http://smartpuffin.com/unit-tests-tutorial/
series: Unit testing
cover_image: https://thepracticaldev.s3.amazonaws.com/i/je4svz9dkykwj4x7pcf3.jpg
---

<i>This post was originally published in my blog <a href="http://smartpuffin.com/unit-tests-tutorial/">smartpuffin.com</a>.</i>

---

Let's imagine we just wrote a method calculating distance between two points on our planet. And let's imagine we want to test it as well as possible. How do we come up with test cases? And what exactly do we need to test?

Bonus: learn a surprising fact about the Fiji islands. 🇫🇯

<!--more-->
<h3>Prerequisites</h3>
I assume you are already familiar with the concepts of unit testing. I'll be using Java and JUnit, but don't worry if you're not familiar with them: the purpose of this tutorial is to learn to write fuller test suites. You'll pick up platform-specific things on the fly.

Here is a link <a href="https://github.com/ice-lenor/ExampleUnitTests">to the repository</a> where I have put the full source code for this post. You can download it and look at it while reading, or look at it afterwards.

And here is my previous article on unit testing topic explaining <a href="https://dev.to/ice_lenor/unit-testing-best-practices-27ec">best practices in unit testing</a> more widely.

Let's go!
<h1>Positive cases</h1>
Let's start with thinking about our method as of a black box.

We have this API:
<pre>
// Returns distance in meters using haversine formula
double getDistance(double latitude1, double longitude1, double latitude2, double longitude2);
</pre>

What can we test?
<h2>Putting yourself in a testing mindset</h2>
You need to switch from being a developer to being a tester now. This means you have to stop trusting yourself. You can't know your code is working if you didn't test it!

If you tested it manually, you don't know if it's going to work next time someone makes a change - in your code or close to it.

Moreover, you can be sure that whatever code you build on top of this well-tested piece, you have one less problem to worry about.

The feeling of security you have when your code is well-tested is incredible. You can refactor freely and develop new features further - and be sure your old code is not going to break.

Promise yourself a treat if you find a bug. But do be careful: too many cookies are bad for your health.

<h2>First test</h2>
Okay, we are ready to test! What should we test first?

The very first thing that comes to mind, is:
<blockquote>Calculate the distance between two points and compare with the true real number calculated manually. If they match, all is well!</blockquote>
And this is a great testing strategy. Let's write some tests for that.

I'll pick a couple of points: one in the very north of the Netherlands, one - in the very south. Practically, I want to measure the country from top to bottom.

I clicked at a couple of points on the map and got this:
<pre>Point 1: latitude = 53.478612, longitude = 6.250578.
Point 2: latitude = 50.752342, longitude = 5.916981.
</pre>
I have used an external website to calculate the distance and got 304001.021046 meters. That means the Netherlands are 304km long!

Now, how do we use this?
<h2>Thinking about domain area</h2>
We need to think about domain area-specific things. Not all of them are obvious from the code: some of them depend on the area, some - on the future plans.

In our example, the returned distance is in meters, and it's a double.

We know that a double is prone to rounding errors. Moreover, we know that the method used in this calculation - the haversine formula - is somewhat imprecise for our oh-so-complex planet. It is enough for our application now, but perhaps, we'll want to replace it with higher-precision calculation.

All this makes us think that we should compare our calculated value with our expected value with some precision.

Let's pick some value that is good for our domain area. To do that, we can remember about our domain area and requirements again. Would 1mm be fine? Probably it would.

And here is our first test!
<pre>double Precision = 0.001; // We are comparing calculated distance using 1mm precision
...
@Test
void distanceTheNetherlandsNorthToSouth() {
    double distance = GeometryHelpers.getDistance(53.478612, 6.250578, 50.752342, 5.916981);
    assertEquals(304001.0210, distance, Precision);
}
</pre>
Let's run this test and make sure it passes. Yay!
<h2>More tests</h2>
We calculated the distance across the Netherlands. But of course, it is a nice idea to double-check and to triple-check.

Your tests should vary - this helps you cast a wider net for these pesky bugs!

Let's find some more nice points. How about we learn how wide Australia is?
<pre>@Test
void distanceAustraliaWestToEast() {
    double distance = GeometryHelpers.getDistance(-23.939607, 113.585605, -28.293166, 153.718989);
    assertEquals(4018083.0398, distance, Precision);
}</pre>
Or how far is it from Capetown to Johannesburg?
<pre>@Test
void distanceFromCapetownToJohannesburg() {
    double distance = GeometryHelpers.getDistance(-33.926510, 18.364603,-26.208450, 28.040572);
    assertEquals(1265065.6094, distance, Precision);
}</pre>
Now that we think about that: are we sure that the distance doesn't depend on the direction in which we are calculating? Let's test that as well!
<pre>@Test
void distanceIsTheSameIfMeasuredInBothDirections() {
    // testing that distance is the same in whatever direction we measure
    double distanceDirection1 = GeometryHelpers.getDistance(-33.926510, 18.364603,-26.208450, 28.040572);
    double distanceDirection2 = GeometryHelpers.getDistance(-26.208450, 28.040572, -33.926510, 18.364603);
    assertEquals(1265065.6094, distanceDirection1, Precision);
    assertEquals(1265065.6094, distanceDirection2, Precision);
}
</pre>
<h1>Corner cases</h1>
Great, we have covered some base cases - the main functionality of the method seems to work.

We can have a cookie now - for going half-way through. 🍪

Now, let's stretch our code to the limit!

Thinking about the domain area helps again.

Our planet is rather a ball than a plane. This means that there is a place where latitude goes from 180 to -180, leaving a "seam" where we should be careful. Math around this area often <a href="https://smartpuffin.com/little-geo-stories-a-tale-of-180th-meridian/">contains mistakes</a>. Does our code handle this well?

A good idea would be to write a test for it, don't you think?

<img src="https://thepracticaldev.s3.amazonaws.com/i/h8fnrkw57iiz0k39a20s.jpg" alt="Screenshot of a map with a two points on it around the Fiji islands" width="840" height="611" />

<pre>@Test
void distanceAround180thMeridianFiji() {
    double distance = GeometryHelpers.getDistance(-17.947826, 177.221232, -16.603513, -179.779055);
    assertEquals(351826.7740, distance, Precision);
}</pre>
Upon further thinking, I discovered one more tricky case - distance between two points which have the same latitude; but the longitude is 180 in one point and -180 in the other.
<pre>double distance = GeometryHelpers.getDistance(20, -180, 20, 180);
// Question to you, my reader: what is this distance?</pre>
Okay, we're done with that weird 180th meridian. We are sure about the 0th meridian though... right? Right? Let's test it too.
<pre>@Test
void distanceAround0thMeridianLondon() {
    double distance = GeometryHelpers.getDistance(51.512722, -0.288552, 51.516100, 0.068025);
    assertEquals(24677.4562, distance, Precision);
}</pre>
What other cases can we come up with? I thought a bit and listed these:
<ul>
 	<li>How about poles? Let's calculate a couple of distances in the Arctic and Antarctica.</li>
 	<li>How about from one pole to another?</li>
 	<li>How about max distance on the planet?</li>
 	<li>How about a really small distance?</li>
 	<li>If both points are absolutely the same, are we getting 0 m distance?</li>
</ul>
I'm not adding all these tests here, as it would take too much space. You can find them <a href="https://github.com/ice-lenor/ExampleUnitTests">in the repo</a>.

You get the point. Try to think creatively. It's a game of coming up with as many ideas as possible.

And don't be afraid with coming up with "too many ideas". The code is never "tested too well".
<h2>What's inside</h2>
At this point, it can also help to <a href="https://github.com/ice-lenor/ExampleUnitTests/blob/master/src/main/java/smartpuffin/com/GeometryHelpers.java">peek inside the code</a>. Do you have the full coverage? Maybe there are some "ifs" and "elses" in the code that may give you a hint?

Do google "haversine formula" and look at its limitations. We already know about precision. Is there something else that could break? Is there some combination of arguments which can make the code return an invalid value? Brainstorm about it.
<h1>Negative cases</h1>
Negative cases are cases when the method is supposed to refuse to do its job. It is a controlled failure!

Again, we should remember about the domain area. Latitude and longitude are special values. Latitude is supposed to be defined in exactly [-90, 90] degrees range. Longitude - in [-180, 180] range. This means that in case when we passed an invalid value, our method throws an exception.

Let's add some tests for that!
<pre>@Test
void invalidLatitude1TooMuch() {
    assertThrows(IllegalArgumentException.class, () -&gt; {
        GeometryHelpers.getDistance(666, 0, 0, 0);
    });
}
</pre>
<pre>@Test
void invalidLatitude1TooLittle() {
    assertThrows(IllegalArgumentException.class, () -&gt; {
        GeometryHelpers.getDistance(-666, 0, 0, 0);
    });
}
</pre>
Same tests we'll add for latitude2, and for both longitude parameters.

We're writing Java here, and the <em>double</em> parameters can't be null. But if you're using a language where they can, test for it!

If you're using a dynamically typed language, and you can pass a string instead of the number, test for it!

Side point: dynamically typed languages will require some more extensive testing than statically typed ones. With the latter, compiler takes care of many things. With the former, it's all in your hands.
<h1>Wrapping up</h1>
You can see and download the source code for this tutorial <a href="https://github.com/ice-lenor/ExampleUnitTests/">here</a>. Look at it and try to come up with some more useful testing scenarios.

{% github ice-lenor/ExampleUnitTests %}

Here's <a href="https://dev.to/ice_lenor/unit-testing-best-practices-27ec">some followup reading</a> to learn about best practices in unit testing.

{% link https://dev.to/ice_lenor/unit-testing-best-practices-27ec %}

For your own projects, select the part that would benefit from testing the most - and try to cover it with tests. Think creatively! Make it a challenge, a competition with yourself!

Unit testing is fun!