Skip to content

Spring Boot Test Mock Bean

DodaTech 1 min read

In this tutorial, you'll learn about Fix Spring Boot Test @MockBean Not Injecting. We cover key concepts, practical examples, and best practices.

The Problem

@MockBean does not inject the mock and the real bean is used in tests.

Quick Fix

Declare @MockBean on field

Wrong:

// @MockBean not on field

Output:

Real bean used

Right:

@MockBean
private UserService userService;

Output:

Mock replaces real bean

Use @SpringBootTest

Wrong:

@WebMvcTest
// Too narrow

Output:

Mock not created

Right:

@SpringBootTest
class UserServiceTest { }

Output:

Full context with mock

Stub mock methods

Wrong:

// thenReturn not called

Output:

Mock returns null

Right:

when(userService.findUser(1L)).thenReturn(new User());

Output:

Mock returns stub data

Prevention

  • Declare @MockBean on the field to mock
  • Use @SpringBootTest for the test context
  • Stub methods with Mockito.when().

Common Mistakes with boot test mock bean

  1. Misunderstanding that String is [Char] with poor performance for large text operations
  2. Using foldl instead of foldl' causing stack overflow on large lists
  3. Forgetting deriving (Show, Eq) on custom data types needed for debugging

These mistakes appear frequently in real-world SPRING code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### Why is the real bean used instead of the mock?

@MockBean must be on a field, and the test must use @SpringBootTest.

This quick fix is part of the DodaTech Spring & JVM ecosystem series. Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro