In this tutorial, you will learn to implement unit test of the service layer in Spring Boot by using Mockito's @Mock and @InjectMock

Project dependencies

Include spring-boot-starter-test into your pom.xml file


spring-boot-starter-test contains some testing support libraries such as JUnit, Spring Test + Spring Boot Test, Mockito, AssertJ, Hamcrest and JsonPath

Define the test class

Run with MockitoJUnitRunner

  • Use @RunWith(MockitoJUnitRunner.class) class annotation to tell JUnit to run the unit tests in Mockito's testing supports

Mock dependencies with Mockito's @InjectMock and @Mock

  • @InjectMock the service you want to test, for example
private ProductService productService;  
  • @Mock the service dependencies, for example
private ProductRespository productRespository;  

Stub methods with Mockito's doReturn...when

  • Using Mockito.doReturn(...).when(aMock).doSomething(...) to give the test input, for example
// given
Product product = Product.builder()  
    .description("P1 desc")
    .price(new BigDecimal("1"))

List<Product> expectedProducts = Arrays.asList(product); 


Verify the test result with AssertJ's assertThat(..).

  • Prefer AssertJ's assertThat to verify the test result for more readability, for example
// when
List<Product> actualProducts = productService.findAll();

// then

Implementation example

Source code