Deep Dive into JUnit + Mockito in Spring Boot
In Spring Boot, we usually use JUnit 5 along with Mockito to write unit and integration tests.
Below are some of the most important annotations and tools you’ll come across while testing your application.
๐งช @Mock
-
This annotation creates a mock object (a dummy object) for a dependency.
-
It does not run any real logic — instead, you define what it should return when a method is called.
๐ Example:
Here, the real database calls are not made. We can use Mockito’s when(...).thenReturn(...) to specify what this mock should return.
๐งฐ @InjectMocks
-
This creates a real instance of the class under test and automatically injects the mock dependencies (created with
@Mock) into it. -
This is mainly used when you are testing the Service layer or any class that has dependencies.
๐ Example:
๐ Why use @InjectMocks?
Without it, you would have to manually create the object like:
@InjectMocks makes this automatic and cleaner.
๐ฟ @MockBean
-
This is used in Spring Test Context (e.g., with
@WebMvcTestor@SpringBootTest). -
It registers a mock bean in the Spring ApplicationContext, replacing the actual bean.
๐ Example:
๐ @MockBean vs @Mock:
-
@Mock→ creates a Mockito mock object only (no Spring involved). -
@MockBean→ creates a mock and replaces the actual Spring bean with it in the ApplicationContext.
๐ธ️ @WebMvcTest
-
This annotation loads only the Spring MVC components required for controller testing.
-
It does not load the entire application context (like services, repositories, etc.).
-
This is used to test the Controller layer in isolation.
๐ Example:
๐งญ MockMvc
-
MockMvcallows you to simulate HTTP requests (GET, POST, etc.) without actually starting the server. -
You can test endpoints, status codes, and responses just like calling APIs from a browser or Postman.
๐ Example:
๐ Summary Table
| Annotation | Purpose | Scope |
|---|---|---|
@Mock | Creates a Mockito mock (no Spring involved) | Plain Unit Tests |
@InjectMocks | Creates real instance and injects mocks into it | Plain Unit Tests |
@MockBean | Registers mock in Spring ApplicationContext, replacing real bean | Spring Context Tests |
@WebMvcTest | Loads only controller-related beans for testing | Controller Layer Testing |
MockMvc | Simulates HTTP requests without running the server | Controller Layer Testing |
✅ How to Choose
-
Service Layer Testing → Use
@Mock+@InjectMocks -
Controller Layer Testing → Use
@WebMvcTest+@MockBean+MockMvc -
Repository Layer Testing → Use
@DataJpaTest(integration with in-memory DB)
This clear separation helps keep tests fast, maintainable, and focused on each layer.
No comments:
Post a Comment