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

<dependency>  
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
</dependency>  

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
@InjectMocks
private ProductService productService;  
  • @Mock the service dependencies, for example
@Mock
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()  
    .name("P1")
    .description("P1 desc")
    .price(new BigDecimal("1"))
    .build();

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

doReturn(expectedProducts).when(productRespository).findAll();  

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
assertThat(actualProducts).isEqualTo(expectedProducts);  

Implementation example


Source code

https://github.com/hellokoding/hellokoding-courses/tree/master/springboot-examples/springboot-restapi-testing-all-layers