Unit Testing with JUnit and Mockito
Test components in isolation.
Unit Testing with JUnit and Mockito is a free Spring Boot 4 Microservices & REST APIs lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Spring Boot 4 Microservices & REST APIs learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Unit Tests
A unit test verifies a single class in isolation, with its collaborators replaced by fakes.
- Fast — no Spring context, no database
- Focused — tests one piece of logic
- Reliable — no external dependencies
JUnit 5 Basics
Spring Boot uses JUnit 5 (Jupiter). A test is a method annotated with @Test.
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class CalculatorTest {
@Test
void addsTwoNumbers() {
assertEquals(5, 2 + 3);
}
}Lifecycle Annotations
Use @BeforeEach to set up state before each test and @AfterEach to clean up.
@BeforeEach
void setUp() {
calculator = new Calculator();
}
@Test
void addsCorrectly() {
assertEquals(7, calculator.add(3, 4));
}AssertJ Fluent Assertions
Spring Boot bundles AssertJ for readable assertions with assertThat.
import static org.assertj.core.api.Assertions.assertThat;
assertThat(result).isEqualTo(42);
assertThat(list).hasSize(3).contains("a");What is Mockito
Mockito creates mock objects — fake implementations of dependencies whose behavior you control.
This lets you test a class without its real collaborators (database, HTTP clients, etc.).
Creating Mocks
Annotate the test class with @ExtendWith(MockitoExtension.class). Use @Mock for dependencies and @InjectMocks for the class under test.
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
@Mock
UserRepository repository;
@InjectMocks
UserService service;
}Stubbing with when/thenReturn
Define a mock's behavior with when(...).thenReturn(...).
@Test
void returnsUserById() {
User alice = new User("1", "Alice");
when(repository.findById("1"))
.thenReturn(Optional.of(alice));
User result = service.getById("1");
assertThat(result.getName()).isEqualTo("Alice");
}Throwing from a Mock
Use thenThrow to simulate error conditions.
when(repository.findById("99"))
.thenThrow(new RuntimeException("DB down"));
assertThrows(RuntimeException.class,
() -> service.getById("99"));Verifying Interactions
verify checks that a mock method was called with expected arguments.
@Test
void savesUser() {
service.create(new User("2", "Bob"));
verify(repository).save(any(User.class));
verify(repository, times(1)).save(any());
}Argument Matchers
Matchers like any(), eq(), and anyString() make stubs flexible.
when(repository.findByName(anyString()))
.thenReturn(List.of(new User("1", "Alice")));
verify(repository).deleteById(eq("1"));Capturing Arguments
ArgumentCaptor captures the value passed to a mock so you can assert on it.
ArgumentCaptor<User> captor =
ArgumentCaptor.forClass(User.class);
verify(repository).save(captor.capture());
assertThat(captor.getValue().getName())
.isEqualTo("Bob");Quick Check
Test your understanding of Mockito.
Recap
You learned to write fast unit tests:
- JUnit 5 with
@Test,@BeforeEach - AssertJ
assertThatfor readable checks - Mockito
@Mock/@InjectMocks when/thenReturnto stub,verifyto confirm calls
Frequently asked questions
Is the “Unit Testing with JUnit and Mockito” lesson free?
Yes — the full text of “Unit Testing with JUnit and Mockito” is free to read here on the web, and the Spring Boot 4 Microservices & REST APIs course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Spring Boot 4 Microservices & REST APIs course, upgrade to CoddyKit PRO.
What will I learn in “Unit Testing with JUnit and Mockito”?
Test components in isolation. You practise Spring Boot 4 Microservices & REST APIs with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Spring Boot 4 Microservices & REST APIs?
No prior experience is required. Spring Boot 4 Microservices & REST APIs on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Unit Testing with JUnit and Mockito” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Spring Boot 4 Microservices & REST APIs lesson?
Yes. Every Spring Boot 4 Microservices & REST APIs lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Unit Testing with JUnit and Mockito
- Web Layer Tests with MockMvc
- Integration Tests with @SpringBootTest
- Real Dependencies with Testcontainers