Using @MockBean to Mock Dependencies in Spring Boot Tests
📖 Scenario: You are building a simple Spring Boot application that manages books. You want to write a test for the BookService class, but it depends on BookRepository which accesses the database. To test BookService without using the real database, you will use @MockBean to create a fake BookRepository.
🎯 Goal: Write a Spring Boot test class that uses @MockBean to mock the BookRepository dependency. Then write a test method that verifies BookService returns the expected book title.
📋 What You'll Learn
Create a
Book class with id and title fieldsCreate a
BookRepository interface with a method findById(Long id)Create a
BookService class that uses BookRepository to get a book by idWrite a test class using
@SpringBootTest and @MockBean to mock BookRepositoryWrite a test method that mocks
findById to return a sample book and asserts the service returns the correct title💡 Why This Matters
🌍 Real World
Mocking dependencies in tests helps you isolate the code you want to test. This avoids using real databases or external services, making tests faster and more reliable.
💼 Career
Understanding @MockBean is essential for writing effective unit and integration tests in Spring Boot applications, a common requirement in Java backend development jobs.
Progress0 / 4 steps