Why tests and what JUnit is
An automated test is a small method that calls your code with known data and checks the result. You write it once and then run hundreds of such checks in a couple of seconds after every change. If a fix in one place breaks something in another, a test tells you right away instead of a user telling you a week later.
In the tutorial you already wrote a first JUnit test. This course goes further: how to organize tests, read failures, test errors and edge cases, and how to replace a database or a mail server with stand-ins.
Three libraries
| Library | What it does |
|---|---|
| JUnit | Finds and runs tests, gives you @Test and the assertions assertEquals, assertThrows and others |
| Mockito | Creates mocks — fake objects that stand in for a database, a mail server or another service |
| AssertJ | Optional: readable chained assertions like assertThat(list).hasSize(2) |
JUnit is the base; the other two plug into it.
Versions
The course uses JUnit 6.1 (6.1.3), Mockito 5.24 and AssertJ 3.27, with Java 25 and Maven. Compared to JUnit 5, version 6 changed little for the test author:
- the minimum Java version is 17;
- all JUnit artifacts now share one version number (before, the platform was 1.x and Jupiter 5.x);
- CSV data for parameterized tests is read by a new parser;
- long-deprecated APIs were removed.
The test API — org.junit.jupiter.api.Test, Assertions, @BeforeEach — is the same as in JUnit 5. The name Jupiter that you see in packages is the name of the modern JUnit programming model.
What we will test
The examples use two small sets of plain Java classes, without any web framework:
PriceCalculatorfrom a shop: the order total and a discount, withBigDecimalamounts;- a blog: the
Postrecord, thePostRepositoryinterface, thePostServiceservice that creates and publishes posts and sends a notification to the author throughNotifier.
The classes are created in the next lesson; tests for them grow from lesson to lesson.
Kinds of tests
| Kind | What it checks | Speed |
|---|---|---|
| Unit test | One class, everything else replaced | Milliseconds |
| Integration test | Several parts together: a service and a real database | Seconds |
| End-to-end test | The whole application through its interface | Minutes |
This course is about unit tests: there should be most of them, and they are what JUnit and Mockito are built for.
Common mistake
Old articles use JUnit 4: import org.junit.Test and org.junit.Assert.assertEquals. In a JUnit 6 project such a test does not compile:
[ERROR] /.../src/test/java/com/example/shop/OldStyleTest.java:[3,17] cannot find symbol
symbol: class Test
location: package org.junitUse the imports from org.junit.jupiter.api — org.junit.jupiter.api.Test and org.junit.jupiter.api.Assertions. Test classes and methods also no longer need to be public.