Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 75

Unit Testing Services with JUnit 5, Mockito, and Jest Comparisons

This lesson is built with resources from youtube.com, javacodegeeks.com and 1 more site.

Hello! Welcome to the first lesson in our new module, "Testing and Integrating the Full System."

In our last module, we successfully built and validated a production-grade CI/CD pipeline capable of deploying our services to Kubernetes with zero downtime. Now that our infrastructure is robust, it's time to shift our focus inward to the quality of the code itself. High-quality code is reliable, maintainable, and easier to debug—and automated testing is the bedrock of achieving that quality.

Today, your goal is to write unit tests for a service class using JUnit 5 and Mockito, comparing mock patterns to Jest. You'll learn how to isolate a single Java class, simulate its dependencies, and verify its logic, a fundamental skill for any backend developer.

What is Unit Testing?

Unit testing is the practice of testing the smallest "units" of your code—typically individual methods or classes—in isolation from the rest of the application. The goal is to verify that each unit behaves exactly as expected.

For example, when testing a PostService, we only want to test the business logic inside the PostService. We don't want to involve the PostRepository, the actual database, or any other part of the system. This isolation is what makes unit tests fast, reliable, and precise.

To get a clear overview of why this is so important, let's start with a short video.

Unit Testing in Spring Boot with JUnit 5 and Mockito | Part 1

The following video from CodeSnippet gives a concise introduction to what unit testing is and why it's a critical practice for professional developers. It sets the stage for everything we'll do today.

Please watch from the beginning until 06:39. Focus on understanding the core idea: testing the smallest component of your application in isolation and the benefits this provides, like early bug detection and confidence in your changes.


The Java Testing Ecosystem: JUnit 5 & Mockito

In the Java world, testing is primarily accomplished with a combination of two libraries that come included with spring-boot-starter-test:

  1. JUnit 5: A framework for writing and running tests. It provides the test runner, assertions (assertEquals, assertTrue), and lifecycle annotations (@Test, @BeforeEach).
  2. Mockito: A framework for creating "mock" objects. Mocks are simulated versions of your dependencies (like repositories or other services) that you control completely, which is how we achieve isolation.

MERN vs. Spring: Mapping Your Testing Knowledge

Your experience with Jest in the MERN stack provides a great foundation. The concepts are very similar, just the syntax and tools are different. Here’s a quick mapping:

Jest Concept (JavaScript/TypeScript) JUnit 5 / Mockito Concept (Java) Description
describe('MyComponent', ...) class MyComponentTest { ... } A test suite is simply a Java class.
test('should do something', ...) @Test void shouldDoSomething() { ... } A single test case is a method annotated with @Test.
jest.fn() or jest.spyOn(...) @Mock or Mockito.mock(...) Creates a mock object (a "test double").
mockImplementation(...) when(...).thenReturn(...) Stubs a method on a mock to return a specific value.
expect(result).toBe(expected) Assertions.assertEquals(expected, result) Asserts that an actual value equals an expected value.
expect(myMock).toHaveBeenCalled() verify(myMock).myMethod() Verifies that a method on a mock was called.
beforeEach(...) / afterEach(...) @BeforeEach / @AfterEach Code to run before/after each test method.

This table should serve as a useful reference as we dive into the code.


Setting Up Your First Test

Before we write code, let's understand the project structure. Spring Boot projects have a standard directory layout that separates application code from test code.

Spring Boot Project Structure for Service Layer Unit Testing
This image shows the standard directory layout for a Spring Boot project. Note how the test directory (`src/test/java`) mirrors the package structure of the main source directory (`src/main/java`), allowing for clean organization of tests.

To create and run a test, you'll need to create a test class and use a few key annotations.

Unit Testing in Spring Boot with JUnit 5 and Mockito | Part 1

This next segment from the same video demonstrates how to create your first test class, where to place it in the project, and how to use the basic @Test annotation.

Please watch from 06:39 to 12:25. This will show you how Spring Boot automatically includes the necessary testing dependencies and how you can create and run a simple, (currently empty) test.


Writing a Service Unit Test: The Arrange-Act-Assert Pattern

A well-structured unit test follows the Arrange-Act-Assert pattern:

  1. Arrange: Set up the test. This includes creating mock objects, defining their behavior (stubbing), and preparing any input data.
  2. Act: Execute the method you are testing.
  3. Assert: Verify the outcome. This could be checking the return value or verifying that your mocks were called correctly.

Let's apply this to a hypothetical PostService. Imagine it has a dependency on PostRepository.

1. Arrange: Mocking Dependencies and Injecting Mocks

To test PostService in isolation, we must provide a mock version of PostRepository. This is where Mockito shines. We use two essential annotations:

  • @Mock: Creates a mock implementation for a class or interface.
  • @InjectMocks: Creates an instance of the class we want to test and automatically injects any fields annotated with @Mock into it.

To enable these, we also need to tell JUnit to use the Mockito extension with @ExtendWith(MockitoExtension.class).

The following video is crucial. It demonstrates exactly how to use these annotations and, more importantly, shows the NullPointerException you get when you don't use them—a perfect example for your "debugging-first" approach.

Unit Testing in Spring Boot with JUnit 5 and Mockito | Part 1

Watch this segment carefully. It walks through creating mocks, injecting them into the service under test, and stubbing their behavior with when().thenReturn().

Watch from 14:22 to 24:06. Pay close attention to how @Mock and @InjectMocks solve the NullPointerException and how when(...).thenReturn(...) is used to control what the mocked repository returns.

Here is a quick reference for the annotations you just saw.

Mockito Annotations Cheat Sheet
A handy cheat sheet for the most common Mockito annotations. We're focusing on `@Mock`, `@InjectMocks`, and `@ExtendWith(MockitoExtension.class)` for now.

2. Assert: Verifying Results and Interactions

After calling your service method, you need to assert that it behaved correctly. This involves two types of checks:

  • State-based verification: Checking the return value. Did the method return the correct data? We use JUnit 5's Assertions for this (e.g., assertEquals).
  • Behavior-based verification: Checking that the method interacted with its dependencies correctly. Did it call the save method on the repository? We use Mockito's verify() for this.

These two videos will show you how to perform both types of assertions.

Unit Testing in Spring Boot with JUnit 5 and Mockito | Part 1

This first clip demonstrates how to use JUnit's Assertions to check the output of your method.

Watch from 24:06 to 27:41. This covers assertEquals, assertNotNull, and assertTrue.

Unit Testing in Spring Boot with JUnit 5 and Mockito | Part 2

This second clip is key. It shows how to use Mockito's verify() to ensure that a dependency's method was called, which is essential for testing methods that don't return a value (void) or have important side effects.

Watch from 07:55 to 12:01. Focus on how verify(mock, times(1)).method() is used to confirm an interaction. This is the direct equivalent of Jest's toHaveBeenCalled().


Your Task: Write Unit Tests for the PostService

Now, let's bring all these concepts together and apply them to our blog platform. Assume you have a PostService and a Post entity. We will create a PostServiceTest class and write our first unit tests.

File to create: src/test/java/com/your-package/blog/posts/PostServiceTest.java

First, you'll need a simple PostService to test. Let's imagine it looks like this:

Post.java (Entity)

// In src/main/java/.../posts/Post.java
public class Post {
    private Long id;
    private String title;
    private String content;
    // Getters and Setters...
}

PostRepository.java (JPA Repository Interface)

// In src/main/java/.../posts/PostRepository.java
import org.springframework.data.jpa.repository.JpaRepository;
public interface PostRepository extends JpaRepository<Post, Long> {
}

PostService.java

// In src/main/java/.../posts/PostService.java
import org.springframework.stereotype.Service;

@Service
public class PostService {

    private final PostRepository postRepository;

    public PostService(PostRepository postRepository) {
        this.postRepository = postRepository;
    }

    public Post createPost(String title, String content) {
        if (title == null || title.isBlank()) {
            throw new IllegalArgumentException("Title cannot be empty.");
        }
        Post newPost = new Post();
        newPost.setTitle(title);
        newPost.setContent(content);
        return postRepository.save(newPost);
    }
    
    public void deletePost(Long id) {
        if (!postRepository.existsById(id)) {
            throw new PostNotFoundException("Post not found with id: " + id);
        }
        postRepository.deleteById(id);
    }
}

Now, write the test class PostServiceTest.java. Use the concepts you've learned.

PostServiceTest.java

// In src/test/java/.../posts/PostServiceTest.java
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

// 1. Enable Mockito
@ExtendWith(MockitoExtension.class)
class PostServiceTest {

    // 2. Create a mock for the dependency
    @Mock
    private PostRepository postRepository;

    // 3. Create an instance of the class under test and inject mocks
    @InjectMocks
    private PostService postService;

    @Test
    void createPost_whenValidData_shouldSaveAndReturnPost() {
        // Arrange
        String title = "My First Post";
        String content = "Hello, World!";
        
        Post postToSave = new Post();
        postToSave.setTitle(title);
        postToSave.setContent(content);

        Post savedPost = new Post();
        savedPost.setId(1L);
        savedPost.setTitle(title);
        savedPost.setContent(content);

        // Stub the repository's save method.
        // `any(Post.class)` is an argument matcher, useful when you don't care about the exact object instance.
        when(postRepository.save(any(Post.class))).thenReturn(savedPost);

        // Act
        Post result = postService.createPost(title, content);

        // Assert
        assertNotNull(result);
        assertEquals(1L, result.getId());
        assertEquals(title, result.getTitle());

        // Verify that the save method was called exactly once with any Post object.
        verify(postRepository, times(1)).save(any(Post.class));
    }
    
    @Test
    void createPost_whenTitleIsEmpty_shouldThrowException() {
        // Arrange
        String title = "";
        String content = "Some content";
        
        // Act & Assert
        // Use assertThrows to verify that the correct exception is thrown.
        IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {
            postService.createPost(title, content);
        });
        
        assertEquals("Title cannot be empty.", exception.getMessage());
        
        // Verify that the repository's save method was NEVER called.
        verify(postRepository, never()).save(any(Post.class));
    }
    
    @Test
    void deletePost_whenPostExists_shouldCallDeleteById() {
        // Arrange
        Long postId = 1L;
        // Stub the repository to report that the post exists.
        when(postRepository.existsById(postId)).thenReturn(true);
        // doNothing() is useful for stubbing void methods.
        doNothing().when(postRepository).deleteById(postId);

        // Act
        // Call the method to be tested.
        postService.deletePost(postId);

        // Assert
        // Verify that deleteById was called exactly once with the correct ID.
        verify(postRepository, times(1)).deleteById(postId);
    }
}

Copy the code above into your IDE, ensure you have the PostService and related classes, and run the tests. They should all pass.


Debugging Task: The Classic NullPointerException

A very common mistake when writing unit tests is forgetting to stub a method call on a mock. Let's see what happens.

  1. In the deletePost_whenPostExists_shouldCallDeleteById test, comment out this line:
    // when(postRepository.existsById(postId)).thenReturn(true);
    
  2. Run the test again. It will now fail.
  3. Your task:
    • Examine the stack trace. What exception is thrown? Where does it originate?
    • Set a breakpoint inside the deletePost method in PostService.
    • Run the test in debug mode. Step through the code and inspect the value returned by postRepository.existsById(id). What is it?
    • Based on your observation, explain why the test is failing and uncomment the line to fix it.

By default, a mocked method that returns a boolean will return false. This causes your if condition to be met, throwing a PostNotFoundException, which is not what the test expected. This exercise trains you to think about the default behavior of mocks and to ensure all necessary interactions are stubbed.


Conclusion

Fantastic work! You've just taken a huge step into backend Java development by learning its most fundamental testing practice.

Key Takeaways:

  • Unit tests focus on a single class in isolation, which is achieved by mocking its dependencies.
  • JUnit 5 provides the testing structure (@Test) and assertions (assertEquals).
  • Mockito provides the tools for creating and controlling mocks (@Mock, when, verify).
  • The Arrange-Act-Assert pattern gives your tests a clean and readable structure.
  • Your knowledge of Jest maps directly to JUnit/Mockito, with describe/test becoming class/method, jest.fn() becoming @Mock, mockReturnValue becoming when/thenReturn, and toHaveBeenCalled becoming verify.

Preview of the Next Lesson:
Testing a service in isolation is crucial, but what about testing the part of your application that handles HTTP requests? In the next lesson, you will learn how to test a REST controller in isolation using @WebMvcTest. This will allow you to test things like request mappings, status codes, and JSON serialization without starting a full web server, building on the mocking skills you developed today.