Summary
For Service layer testing, you usually write pure unit tests — meaning:
The Spring context is not loaded
Dependencies (repositories, API clients, etc.) are mocked
So you’re testing only that one class and its logic.
So just plain Junit5 is needed to test. No need for any application context load.
Example
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
@Mock
private OrderRepository orderRepository; // dependency
@InjectMocks
private OrderService orderService; // class under test
@Test
void placeOrder_savesOrderWhenValid() {
// Arrange
Order order = new Order(1L, "Shoes", 2);
when(orderRepository.save(order)).thenReturn(order);
// Act
Order result = orderService.placeOrder(order);
// Assert
assertThat(result).isNotNull();
verify(orderRepository).save(order);
}Why cant I use @MockBean
@MockBean is a Spring Boot testing annotation that: Replaces a real Spring Bean in the ApplicationContext with a Mockito mock.
That means — @MockBean only works when Spring has started a test context, e.g.:
@SpringBootTest
@WebMvcTest
@DataJpaTest
In a pure JUnit + Mockito test, you’re not starting the Spring container. That means there is no ApplicationContext — no beans, no autowiring. This fails because @MockBean expects Spring to manage the mock inside a running Spring context, but here, only JUnit and Mockito are running — not Spring Boot.