The first time a bug reached production because of a change I made, I was told the same thing three times: "Did you test it?" I had. I had run the program, clicked around and it looked fine. But "it looked fine when I tried it" is not a test. It's a hope.
Unit tests turn that hope into a safety net. They're small programs that check your code for you, in milliseconds, every time you change something. In Java, the most popular tool for writing them is JUnit .
In this post, we'll look at how testing used to work, what unit testing and TDD are, how JUnit 5 differs from JUnit 4, how JUnit 5 is built, how to set it up with Maven and Surefire, and then the main assertions and annotations you'll use every day.
A quick version note: JUnit's newest major version is JUnit 6 (released in September 2025). It needs Java 17, and the Jupiter API you learn here carries over to it. I'm using JUnit 5 because it still runs on older Java versions and is everywhere in existing projects.…