In this article, we’re going to dive into the spring-boot-starter-test dependency that’s used for writing tests in Spring Boot projects. We’ll go over the important libraries included in this dependency, with a focus on JUnit and Mockito, and even provide some sample codes related to these libraries.
spring-boot-starter-test dependency includes the following important libraries:
-JUnit
-Spring Test
-AssertJ
-Hamcrest
-Mockito
-JSONassert
-JsonPath
Practice
-DrugService
@Service
public class DrugService {
private final DrugRepository drugRepository;
public DrugService(DrugRepository drugRepository) {
this.drugRepository = drugRepository;
}
public Drug save(SaveDrugDto dto) {
Drug drug = new Drug();
drug.setDrugName(dto.drugName());
drug.setCompanyName(dto.companyName());
drug.setStock(dto.stock());
return drugRepository.save(drug);
}
public Optional<Drug> findById(Long id) {
return drugRepository.findById(id);
}
}
We will write a test class for the two methods in the DrugService class.

It is recommended to maintain the package structure in the main part when writing the test. This isn’t necessary, but it will make it easier to understand and access.
-DrugServiceTest
@ExtendWith(MockitoExtension.class)
@DisplayName("Drug service test class")
class DrugServiceTest {
@Mock
private DrugRepository drugRepository;
@InjectMocks
private DrugService drugService;
@Test
@DisplayName("Saving drug")
void shouldSaveDrugSuccessfully() {
// Given
SaveDrugDto dto = new SaveDrugDto("Sodium Chloride", "Baxter Healthcare Corporation", 809);
Drug savedDrug = new Drug();
savedDrug.setId(1L);
savedDrug.setDrugName(dto.drugName());
savedDrug.setCompanyName(dto.companyName());
savedDrug.setStock(dto.stock());
// Mock the calls
when(drugRepository.save(any(Drug.class))).thenReturn(savedDrug);
// When
Drug result = drugService.save(dto);
// Then
assertEquals(savedDrug.getId(), result.getId());
assertEquals(savedDrug.getDrugName(), result.getDrugName());
assertEquals(savedDrug.getCompanyName(), result.getCompanyName());
assertEquals(savedDrug.getStock(), result.getStock());
verify(drugRepository).save(any(Drug.class));
}
@Test
@DisplayName("Find drug by id - Success")
void shouldFindDrugById_Success() {
// Given
Long drugId = 1L;
Drug mockDrug = new Drug();
mockDrug.setId(drugId);
mockDrug.setDrugName("Bacitracin Zinc");
mockDrug.setCompanyName("Dynarex Corporation");
mockDrug.setStock(704);
// Mock the calls
when(drugRepository.findById(drugId)).thenReturn(Optional.of(mockDrug));
// When
Optional<Drug> result = drugService.findById(drugId);
// Then
assertTrue(result.isPresent());
assertEquals(mockDrug, result.get());
verify(drugRepository).findById(drugId);
}
@Test
@DisplayName("Find drug by id - Not Found")
void shouldFindDrugById_NotFound() {
// Given
Long nonExistingDrugId = 2L;
when(drugRepository.findById(nonExistingDrugId)).thenReturn(Optional.empty());
// When
Optional<Drug> result = drugService.findById(nonExistingDrugId);
// Then
assertEquals(Optional.empty(), result);
verify(drugRepository).findById(nonExistingDrugId);
}
}
If I want to run the service class and write tests, as in the example above, I do not have to create a real repository instance or object. For this, I use Mockito, which is a Java testing framework. This framework allows you to create mock-ups of objects during testing.
While writing the test of the service class, we use the @Mock annotation for the repository and the @InjectMocks annotation for the service class (the class for which the test is written) so that the class marked with @Mock is automatically injected by the class marked with @InjectMocks.
Given: Here, we prepare the test environment.
Mock the calls using the when(...).thenReturn(...) statement, which allows us to return a predefined object when a class instance is passed to it.
When: This part executes the method under test.
Then: The assertions validate the outcome.
There are a few types of assertions that we can use, such as assertTrue, which checks that a supplied condition is true, assertEquals, which checks that the expected and actual values are equal.
We use the verify method to check if a specific method of a mock object has been called with specified arguments.
You can access the source code by following this link.
References
https://docs.spring.io/spring-boot/docs/1.5.2.RELEASE/reference/html/boot-features-testing.html
https://junit.org/junit5/docs/current/user-guide/
https://www.javadoc.io/static/org.mockito/mockito-junit-jupiter/5.10.0/org/mockito/junit/jupiter/MockitoExtension.html
https://junit.org/junit4/javadoc/4.8/org/junit/Assert.html
https://github.com/junit-team/junit5-samples