Featured Article

Spring Boot Mockito Example: Master Testing With Step By Step Guide

Kenneth Jul 13, 2026

Spring Boot and Mockito are two powerful tools that have transformed the way developers approach enterprise application development and testing. While Spring Boot simplifies application development, Mockito facilitates the creation of efficient, reliable, and readable mocks for unit tests. When combined, they can significantly enhance your coding productivity and ensure code stability.

30+ Refreshing Spring Mojito Recipes to Try This Season
30+ Refreshing Spring Mojito Recipes to Try This Season

In this comprehensive guide, we will delve into the world of Spring Boot and Mockito, and provide you with a practical example of how to use Mockito for testing a Spring Boot application. By the end, you will have a solid understanding of how to leverage Mockito to create more effective unit tests in your Spring Boot projects.

Spring Mocktails for Pregnant Moms
Spring Mocktails for Pregnant Moms

Understanding Mockito in Spring Boot

Before we dive into the example, let's briefly understand what Mockito is and why it's crucial for testing Spring Boot applications. Mockito is a popular Java library used for creating mocks or fake objects to isolate the code under test from real dependencies. It allows developers to test the behavior of a class or method in isolation, making the test faster, more reliable, and easier to understand.

someone is mixing something in a bowl with a spoon on a wooden table next to a plant
someone is mixing something in a bowl with a spoon on a wooden table next to a plant

In the context of Spring Boot, Mockito is invaluable because it enables developers to test the application's components without depending on external services, databases, or other resources. This is particularly useful for unit tests, where the focus is on testing a specific component's behavior in isolation.

Setting Up the Mockito Environment

kiwi mint mojito cocktail recipe in a glass
kiwi mint mojito cocktail recipe in a glass

To use Mockito in your Spring Boot project, you'll need to add the Mockito BOM (Bill of Materials) and the Mockito dependency to your `build.gradle` or `pom.xml` file. Here's an example using Gradle:

```groovy dependencies { testImplementation 'org.mockito:mockito-core:3.11.2' testImplementation 'org.mockito:mockito-junit-jupiter:3.11.2' } ```

The Mockito BOM ensures that all Mockito dependencies have the same version, preventing potential conflicts. The `mockito-core` dependency provides the core Mockito functionality, while `mockito-junit-jupiter` integrates Mockito with JUnit 5.

Creating Mocks with Mockito

the ultimate cocktail guide for every type of drinker in the world, including drinks and beverages
the ultimate cocktail guide for every type of drinker in the world, including drinks and beverages

Once you've set up the environment, you can start creating mocks using Mockito's annotations and methods. For example, here's how you can create a mock of a `CustomerService` using Mockito:

```java import static org.mockito.Mockito.*; describe("CustomerServiceTest") { val customerService = mock(CustomerService::class.java) it("should return a list of customers") { // Arrange val expectedCustomers = listOf(Customer("John"), Customer("Jane")) whenever(customerService.getCustomers()).thenReturn(expectedCustomers) // Act val result = customerService.getCustomers() // Assert assertEquals(expectedCustomers, result) } } ```

In this example, we're using the `mock` function from Mockito to create a mock of `CustomerService`. We then use the `whenever` function to define the behavior of the mock when the `getCustomers` method is called. Finally, we call the `getCustomers` method on the mock and assert that the result matches the expected output.

Spring Boot Example: Testing a RestController with Mockito

🍊 20 Refreshing Spring Mocktails You Need to Try for Sunny Days 🌼
🍊 20 Refreshing Spring Mocktails You Need to Try for Sunny Days 🌼

Now that we have a basic understanding of how to use Mockito, let's look at a more complex example involving a Spring Boot `RestController`. In this case, we'll create a simple `CustomerController` and test its behavior using Mockito.

Imagine we have the following `CustomerController`:

Kiwi Mocktail | Kiwi Mojito Non Alcoholic Drink - The Mindful Mocktail
Kiwi Mocktail | Kiwi Mojito Non Alcoholic Drink - The Mindful Mocktail
Frozen Mojito Mocktail
Frozen Mojito Mocktail
the ingredients for this drink are displayed on a table
the ingredients for this drink are displayed on a table
4-ingredient Mocktail Three Ways, Spicy Blood Orange Mocktail, Year-round Mocktail Recipes, Arbonne Blood Orange Fizz, Xyngular Collagen, Mocktail Orange Crush, Mojito Collagen Mocktail, Melaleuca Drink, Arbonne Fizz Mocktails
4-ingredient Mocktail Three Ways, Spicy Blood Orange Mocktail, Year-round Mocktail Recipes, Arbonne Blood Orange Fizz, Xyngular Collagen, Mocktail Orange Crush, Mojito Collagen Mocktail, Melaleuca Drink, Arbonne Fizz Mocktails
Best Mojito Recipes
Best Mojito Recipes
Eskimo 24 wool tweed fabric Luxury Wool Boots For Winter, Wool Boots, Inuikii Snow Boots, How To Style Mou Boots, Mou Boots Preppy, Mou Shoes, Mou Glacier Boots, Mou Ankle Boots, Mou Wedge Boots
Eskimo 24 wool tweed fabric Luxury Wool Boots For Winter, Wool Boots, Inuikii Snow Boots, How To Style Mou Boots, Mou Boots Preppy, Mou Shoes, Mou Glacier Boots, Mou Ankle Boots, Mou Wedge Boots
🍹 Kiwi Strawberry Springtime Mocktail – A Fruity Spring Mocktail
🍹 Kiwi Strawberry Springtime Mocktail – A Fruity Spring Mocktail
Beige Ankle Boot Heeled Boots For Fall, Neutral Color Ankle Boots, Beige Stacked Heel Boots For Spring, Beige Almond Toe Heeled Boots For Spring, Casual Taupe Ankle Boots, Taupe Ankle Boots For Spring, Beige Boots With Stacked Heel For Spring, Neutral Ankle Boots, Cream Ankle Boot Heels For Fall
Beige Ankle Boot Heeled Boots For Fall, Neutral Color Ankle Boots, Beige Stacked Heel Boots For Spring, Beige Almond Toe Heeled Boots For Spring, Casual Taupe Ankle Boots, Taupe Ankle Boots For Spring, Beige Boots With Stacked Heel For Spring, Neutral Ankle Boots, Cream Ankle Boot Heels For Fall
5-Minute Coconut Blueberry Mint Mocktail - No Blender Needed
5-Minute Coconut Blueberry Mint Mocktail - No Blender Needed

```java @RestController @RequestMapping("/api/customers") class CustomerController(private val customerService: CustomerService) { @GetMapping fun getCustomers(): List = customerService.getCustomers() } ```

To test this controller, we can create a mock of `CustomerService` and use Mockito to define its behavior. Here's an example of how you can do this using JUnit 5 and Mockito:

```java import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest import org.springframework.boot.test.mock.mockito.MockBean import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status import org.springframework.test.web.servlet.result.MockMvcResultMatchers.content @WebMvcTest(CustomerController::class) class CustomerControllerTest { @Autowired private lateinit var mockMvc: MockMvc @MockBean private lateinit var customerService: CustomerService @BeforeEach fun setUp() { whenever(customerService.getCustomers()).thenReturn(listOf(Customer("John"), Customer("Jane"))) } @Test fun `getCustomers returns a list of customers`() { mockMvc.perform(get("/api/customers")) .andExpect(status().isOk) .andExpect(content().json("[{\"name\":\"John\"}, {\"name\":\"Jane\"}]")) } } ```

In this example, we're using the `@WebMvcTest` annotation to test the `CustomerController` in isolation. The `@MockBean` annotation tells Spring to create a mock of `CustomerService` and inject it into the controller. In the `setUp` method, we define the behavior of the mock using Mockito's `whenever` function. Finally, in the test method, we use the `MockMvc` object to send a `GET` request to the `/api/customers` endpoint and assert that the response status is `200 OK` and the response body matches the expected JSON output.

Testing Exception Handling with Mockito

In addition to testing the normal behavior of your Spring Boot components, you can also use Mockito to test how they handle exceptions. For example, you can modify the behavior of the `CustomerService` mock to throw an exception and verify that the `CustomerController` handles it correctly:

```java @Test fun `getCustomers throws an exception`() { whenever(customerService.getCustomers()).thenThrow(RuntimeException::class.java) mockMvc.perform(get("/api/customers")) .andExpect(status().isInternalServerError) .andExpect(content().string("An internal server error occurred")) } ```

In this example, we're changing the behavior of the `CustomerService` mock to throw a `RuntimeException` when the `getCustomers` method is called. We then send a `GET` request to the `/api/customers` endpoint and assert that the response status is `500 Internal Server Error` and the response body matches the expected error message.

Again, we're using Mockito to define the behavior of a dependency (in this case, `CustomerService`), allowing us to test the behavior of another component (the `CustomerController`) in isolation.

Best Practices for Using Mockito in Spring Boot

When using Mockito in your Spring Boot projects, there are a few best practices to keep in mind:

Be Specific with Mocks

Avoid creating mocks of entire layers of your application (e.g., the entire `CustomerService` layer). Instead, focus on creating mocks of specific dependencies to isolate the code under test. This makes your tests faster, more reliable, and easier to understand.

Spy vs. Mock

Mockito allows you to create spies, which are partial mocks that delegate some method calls to the real implementation. Spies can be useful when you want to test the behavior of a class in the presence of certain dependencies but don't want to mock those dependencies entirely. However, use spies sparingly, as they can make your tests more complex and harder to understand.

Stubbing and Verification

When defining the behavior of a mock, you can use Mockito's `when` and `then` functions for simple mocking scenarios. However, for more complex scenarios, consider using Mockito's `arg-matchers` to define the expected input and `answer` to define the expected output. Similarly, use Mockito's `verify` functions to verify that the expected method calls were made on the mock.

Keep Your Tests Independent

To ensure that your tests are fast, reliable, and easy to understand, keep them independent of each other. This means that each test should define the behavior of its mocks explicitly, rather than relying on a shared state. You can achieve this by using the `@BeforeEach` annotation to set up the mocks for each test, as we did in the previous examples.

By following these best practices, you can create more effective unit tests for your Spring Boot applications using Mockito.

In the world of enterprise application development, Spring Boot and Mockito have emerged as powerful tools for streamlining the development and testing processes. By leveraging the power of Spring Boot for application development and Mockito for unit testing, you can build more reliable, maintainable, and efficient code. The combination of these two tools can significantly enhance your coding productivity and ensure the stability of your applications.