Unit Testing - a Starter for Ten

A very basic intro for complete beginners. Part of the Starter for Ten series.

So what actually is unit testing?

You write some code. Then you write some extra code that tests whether your original code does what you expect it to do*. That's unit testing.

You typically use something called a 'testing framework' to write those tests and run them. JUnit is the most common Java testing framework. Jest is the most common JavaScript testing framework.

What even is a 'testing framework'? It's a bunch of code that some clever developers have written for you. You can just use it in your own code, straight out of the box and it will do the job for you. You just have to 'import' it (see the example unit test below). The documentation will tell you how to use it.

You write the test code in a separate file to the one that contains your original code. As long as you give the test file the correct name and store it in the correct place in the project folder, the testing framework is clever enough to work out which original code the test you have written is for.

Here's an example of a unit test…

Let's say your original code takes in an email address and transforms it to lower case characters. becomes .

You could write a unit test to check that when you pass in HermioneGranger@Hogwarts.Co.UK, you get hermionegranger@hogwarts.co.uk back.

Your original code might look something like this:

public class EmailFormatter {

    public String toLowerCase (String email) {
        return email.toLowerCase();
    }
}

Your unit test code, would look something like this:

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

class EmailFormatterTest {

    @Test
    void upperCaseCharactersShouldBeReplacedWithLowerCase() {
        var emailFormatter = new EmailFormatter();

        String expected = "hermionegranger@hogwarts.co.uk";
        String result = emailFormatter.toLowerCase("HermioneGranger@Hogwarts.Co.UK");

        assertEquals(expected, result);
    } 
}

You can then 'run' your unit test and it will tell you whether the test passes or fails. Most IDEs (such as VSCode or IntelliJ) have an option where you can click a 'play' button next to the unit test to run it.

You would usually write more than one unit test to cover all the possible scenarios. Once you've got a set of really robust unit tests in place, you (or someone else) can change your original code with confidence, knowing that if you accidentally break it, it will be caught by your unit tests.

Want to learn more?

https://www.youtube.com/watch?v=vZm0lHciFsQ


*unless you're following a thing called Test-Driven Development, then you'd actually write the test first. But that's more than we need to know for now...