Tuesday, August 12, 2025

Mastering Unit Testing in Spring Boot – Part 2: Setting Up JUnit 5 & Mockito

 Last time, we learned why testing matters and met our new best friends: JUnit 5 & Mockito. Now it’s time to invite them into our Spring Boot project and get everything ready for action.




⚙️ Step 1: Start with a Spring Boot Project

If you don’t already have a project, head over to Spring Initializr and create one:

  • Project: Maven (or Gradle if that’s your jam)

  • Language: Java

  • Spring Boot: Latest stable version

  • Dependencies: Spring Web, Spring Boot DevTools

Download and unzip your project, then open it in your favorite IDE (IntelliJ, VS Code, Eclipse — I won’t judge… much).


πŸ“¦ Step 2: Add JUnit 5 & Mockito Dependencies

If you created a Spring Boot 2.2+ project, JUnit 5 is already the default test engine.
But let’s make sure everything is explicit.

Maven (pom.xml):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<dependencies>
    <!-- Spring Boot Test Starter (includes JUnit 5 by default) -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <!-- Exclude JUnit 4 -->
            <exclusion>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <!-- Mockito Core -->
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>5.11.0</version>
        <scope>test</scope>
    </dependency>
</dependencies>

(Gradle folks: you’ll need testImplementation 'org.mockito:mockito-core:5.11.0' in build.gradle.)


πŸ›  Step 3: Understanding the Structure

When you create a Spring Boot project, your folders will look like this:

1
2
3
4
5
6
src
 ├── main
     └── java         # Your main code
 
 └── test
      └── java         # Your test code

Tests for src/main/java/com.example.demo/service/MyService.java
should live in src/test/java/com.example.demo/service/MyServiceTest.java.


πŸ§ͺ Step 4: Your First JUnit 5 Test

Let’s make sure our setup is working. Create a file:
src/test/java/com/example/demo/HelloWorldTest.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package com.example.demo;

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

class HelloWorldTest {

    @Test
    void shouldReturnHelloWorld() {
        String greeting = "Hello World";
        assertEquals("Hello World", greeting);
    }
}

Run this test. If it passes ✅ — congrats! You’ve just run your first JUnit 5 test in Spring Boot.


🎭 Step 5: Adding Mockito

Let’s pretend we have a service that depends on a repository.

src/main/java/com/example/demo/service/GreetingService.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
package com.example.demo.service;

import org.springframework.stereotype.Service;

@Service
public class GreetingService {
    private final GreetingRepository repository;

    public GreetingService(GreetingRepository repository) {
        this.repository = repository;
    }

    public String getGreeting() {
        return repository.fetchGreeting();
    }
}

src/main/java/com/example/demo/service/GreetingRepository.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
package com.example.demo.service;

import org.springframework.stereotype.Repository;

@Repository
public class GreetingRepository {
    public String fetchGreeting() {
        return "Hello from the database!";
    }
}

Now, let’s test the service without touching the real repository.

src/test/java/com/example/demo/service/GreetingServiceTest.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.example.demo.service;

import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import static org.mockito.Mockito.when;
import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.extension.ExtendWith;

@ExtendWith(MockitoExtension.class)
class GreetingServiceTest {

    @Mock
    GreetingRepository repository;

    @InjectMocks
    GreetingService service;

    @Test
    void shouldReturnMockedGreeting() {
        when(repository.fetchGreeting()).thenReturn("Hello from Mockito!");

        String result = service.getGreeting();

        assertEquals("Hello from Mockito!", result);
    }
}

Run the test → green bar → happy developer.


🎨 The “Coffee Analogy” Continues

In Part 1, JUnit was our taste tester and Mockito our fake milk supplier.
Now, we’ve actually given them a kitchen to work in (Spring Boot) and stocked it with ingredients (dependencies).
We can start making mock cappuccinos at full speed.



✅ Next in Part 3

We’ll write real unit tests for a Spring Boot REST controller and see how to mock external APIs.

Remember:

Tests don’t slow you down — bugs do.

No comments:

Post a Comment

Mastering Unit Testing in Spring Boot – Part 2: Setting Up JUnit 5 & Mockito

  Last time, we learned why testing matters and met our new best friends: JUnit 5 & Mockito. Now it’s time to invite them into our Spri...