Backend Development 28 min read

Comprehensive Guide to Unit Testing with Mockito, PowerMock, and JUnit in Spring Boot

This article explains the fundamentals of unit testing in Java, covering what unit tests are, why they matter, when to write them, and detailed step‑by‑step examples using Mockito, PowerMock, JUnit, and Spring Boot to mock dependencies, verify behavior, and assert results across DAO, service, and controller layers.

Sohu Tech Products
Sohu Tech Products
Sohu Tech Products
Comprehensive Guide to Unit Testing with Mockito, PowerMock, and JUnit in Spring Boot

1. What is Unit Testing

Unit testing is the practice of verifying the correctness of the smallest testable parts of a program, such as individual methods in Java classes.

2. Significance of Unit Tests

Unit tests improve code quality, reduce bugs during integration, speed up debugging, protect refactoring, and help developers understand code behavior.

2.1 When to Write Unit Tests

Tests can be written before code (TDD), alongside code, or after code; the earlier the better.

2.2 Scenarios Requiring Unit Tests

Focus on complex calculations, utility classes, intricate logic, and core business code.

3. Unit Testing Approach in Spring Boot

Add the testing starter dependency:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
</dependency>

Spring Boot provides JUnit, Mockito, and other libraries out of the box.

3.1 Mock Introduction

Mock objects replace real dependencies, allowing isolation of the class under test.

3.2 Using Mockito

Typical annotations:

@Mock
private Dependency dependency;

@InjectMocks
private ClassUnderTest classUnderTest;

Example of stubbing and verification:

when(dependency.call()).thenReturn(value);
classUnderTest.method();
verify(dependency).call();

3.3 AssertThat with Hamcrest

AssertThat provides readable assertions:

assertThat(result, is(equalTo(expected)));
assertThat(string, containsString("sub"));

3.4 Unit Test Examples

DAO Layer

Testing a DAO method can be done by mocking the database or using an in‑memory DB, but pure unit tests usually mock the mapper:

@RunWith(MockitoJUnitRunner.class)
public class BusinessAgentRepositoryTest {
  @Mock private BusinessAgentExtMapper mapper;
  @InjectMocks private BusinessAgentRepository repository;

  @Test
  public void save_whenExists_updates() {
    BusinessAgent agent = new BusinessAgent();
    agent.setTelOrigin("13888888888");
    doReturn(true).when(repository).exist("13888888888");
    int id = repository.save(agent);
    verify(mapper).updateByPrimaryKeySelective(agent);
    verify(mapper, never()).insert(agent);
    assertThat(id, equalTo(agent.getAgentId()));
  }
}

Service Layer

Service tests mock DAOs and other services, set up data, and verify business logic:

@RunWith(MockitoJUnitRunner.class)
public class CountServiceTest {
  @Mock private NewsDAO newsDAO;
  @Mock private UserVestService userVestService;
  @InjectMocks private CountService countService;

  @Test
  public void getUserNewsStatisticsByRate_normal() {
    // arrange data, stub DAO calls, then call service method
    // assert response matches expected
  }
}

Controller Layer

Use MockMvc to test Spring MVC controllers without starting the server:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
public class InvalidPicControllerTest {
  @Autowired private MockMvc mockMvc;
  @MockBean private InvalidPicService invalidPicService;

  @Test
  public void invalidHousePicByUrl() throws Exception {
    mockMvc.perform(get("/invalidHousePicByUrl").param("url", "111"))
           .andExpect(status().isOk())
           .andExpect(content().string("ok"));
    verify(invalidPicService).invalidHousePic("111");
  }
}

4. PowerMock for Advanced Mocking

PowerMock extends Mockito/EasyMock to mock static methods, constructors, private methods, and final methods.

Example of mocking a static method:

@RunWith(PowerMockRunner.class)
@PrepareForTest(LocalStringUtils.class)
public class ExampleTest {
  @Test
  public void testStatic() {
    PowerMockito.mockStatic(LocalStringUtils.class);
    when(LocalStringUtils.removeHtmlLabel(null)).thenReturn("test");
    assertThat(LocalStringUtils.removeHtmlLabel(null), is("test"));
  }
}

PowerMock can also mock constructors:

File mockFile = mock(File.class);
PowerMockito.whenNew(File.class).withArguments("c:/Users").thenReturn(mockFile);
when(mockFile.exists()).thenReturn(true);
assertThat(mockFile.exists(), is(true));

5. Underlying Principles

Mockito creates proxy objects that record method calls and return stubbed values. PowerMock uses a custom class loader and byte‑code manipulation to replace static, final, and private implementations.

References: CSDN blog, Spring Boot tutorials, Hamcrest documentation, PowerMock GitHub.

JavaUnit TestingmockingSpring BootJunitPowerMockMockito
Sohu Tech Products
Written by

Sohu Tech Products

A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.