Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

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

LibraryWhat it does
JUnitFinds and runs tests, gives you @Test and the assertions assertEquals, assertThrows and others
MockitoCreates mocks — fake objects that stand in for a database, a mail server or another service
AssertJOptional: 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:

  • PriceCalculator from a shop: the order total and a discount, with BigDecimal amounts;
  • a blog: the Post record, the PostRepository interface, the PostService service that creates and publishes posts and sends a notification to the author through Notifier.

The classes are created in the next lesson; tests for them grow from lesson to lesson.

Kinds of tests

KindWhat it checksSpeed
Unit testOne class, everything else replacedMilliseconds
Integration testSeveral parts together: a service and a real databaseSeconds
End-to-end testThe whole application through its interfaceMinutes

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.junit

Use 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.

Thanks for reading!

Donate to the site — we work hard for you.