TP9.1 - Unit Tests of the Service Layer
Objectives of the TP
In this TP, you will:
- ✅ Test a complete ProductService with Mockito
- ✅ Cover nominal and error cases
- ✅ Use @Mock and @InjectMocks
- ✅ Verify interactions with verify()
- ✅ Achieve high code coverage
Estimated duration: 1h30
Context
You have a ProductService that manages e-commerce products. You need to test all its methods without using a database.
Part 1: The Code to Test
Product Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Product {
private Long id;
private String name;
private String description;
private BigDecimal price;
private Integer stock;
private boolean active;
}
ProductRepository
public interface ProductRepository extends JpaRepository<Product, Long> {
List<Product> findByActiveTrue();
List<Product> findByPriceLessThan(BigDecimal price);
Optional<Product> findByName(String name);
}
ProductService
@Service
@RequiredArgsConstructor
public class ProductService {
private final ProductRepository productRepository;
public List<Product> findAll() {
return productRepository.findAll();
}
public Product findById(Long id) {
return productRepository.findById(id)
.orElseThrow(() -> new ProductNotFoundException("Product not found: " + id));
}
public Product create(Product product) {
if (product.getName() == null || product.getName().isBlank()) {
throw new IllegalArgumentException("Product name is required");
}
if (product.getPrice() == null || product.getPrice().compareTo(BigDecimal.ZERO) <= 0) {
throw new IllegalArgumentException("Price must be positive");
}
product.setActive(true);
return productRepository.save(product);
}
public Product update(Long id, Product updated) {
Product existing = findById(id);
existing.setName(updated.getName());
existing.setDescription(updated.getDescription());
existing.setPrice(updated.getPrice());
existing.setStock(updated.getStock());
return productRepository.save(existing);
}
public void delete(Long id) {
if (!productRepository.existsById(id)) {
throw new ProductNotFoundException("Product not found: " + id);
}
productRepository.deleteById(id);
}
public List<Product> findActiveProducts() {
return productRepository.findByActiveTrue();
}
public void deactivate(Long id) {
Product product = findById(id);
product.setActive(false);
productRepository.save(product);
}
public boolean isInStock(Long id) {
Product product = findById(id);
return product.getStock() != null && product.getStock() > 0;
}
public void decreaseStock(Long id, int quantity) {
Product product = findById(id);
if (product.getStock() < quantity) {
throw new InsufficientStockException("Not enough stock");
}
product.setStock(product.getStock() - quantity);
productRepository.save(product);
}
}
Part 2: Create the Test Class
Basic Structure
@ExtendWith(MockitoExtension.class)
class ProductServiceTest {
@Mock
private ProductRepository productRepository;
@InjectMocks
private ProductService productService;
private Product sampleProduct;
@BeforeEach
void setUp() {
sampleProduct = new Product(1L, "Laptop", "High-end laptop",
new BigDecimal("999.99"), 10, true);
}
}
Part 3: Tests to Implement
Test 1: findAll()
@Test
@DisplayName("findAll should return all products")
void findAll_ShouldReturnAllProducts() {
// Arrange
List<Product> products = List.of(
sampleProduct,
new Product(2L, "Phone", "Smartphone", new BigDecimal("599.99"), 20, true)
);
when(productRepository.findAll()).thenReturn(products);
// Act
List<Product> result = productService.findAll();
// Assert
assertThat(result).hasSize(2);
verify(productRepository).findAll();
}
Test 2: findById() - Success
@Test
@DisplayName("findById should return the product when it exists")
void findById_WhenExists_ShouldReturnProduct() {
// TODO: Implement
// Hint: when(...).thenReturn(Optional.of(...))
}
Test 3: findById() - Not Found
@Test
@DisplayName("findById should throw an exception when the product does not exist")
void findById_WhenNotExists_ShouldThrowException() {
// TODO: Implement
// Hint: when(...).thenReturn(Optional.empty())
// assertThrows(ProductNotFoundException.class, ...)
}
Test 4: create() - Success
@Test
@DisplayName("create should save and return the product")
void create_WithValidProduct_ShouldSaveAndReturn() {
// TODO: Implement
// Verify that the product is marked active
// Verify that save() is called
}
Test 5: create() - Validation Name
@Test
@DisplayName("create should throw an exception if the name is empty")
void create_WithEmptyName_ShouldThrowException() {
// TODO: Implement
// assertThrows(IllegalArgumentException.class, ...)
// verify(productRepository, never()).save(any())
}
Test 6: create() - Validation Price
@Test
@DisplayName("create should throw an exception if the price is negative")
void create_WithNegativePrice_ShouldThrowException() {
// TODO: Implement
}
Test 7: update()
@Test
@DisplayName("update should modify and save the product")
void update_ShouldModifyAndSave() {
// TODO: Implement
// Verify that fields are updated
}
Test 8: delete() - Success
@Test
@DisplayName("delete should remove the existing product")
void delete_WhenExists_ShouldDelete() {
// TODO: Implement
// when(existsById).thenReturn(true)
// verify deleteById
}
Test 9: delete() - Not Found
@Test
@DisplayName("delete should throw an exception if the product does not exist")
void delete_WhenNotExists_ShouldThrowException() {
// TODO: Implement
}
Test 10: deactivate()
@Test
@DisplayName("deactivate should set active to false")
void deactivate_ShouldSetActiveFalse() {
// TODO: Implement
// Use ArgumentCaptor to verify the saved value
}
Test 11: isInStock() - True
@Test
@DisplayName("isInStock should return true if stock > 0")
void isInStock_WhenStockPositive_ShouldReturnTrue() {
// TODO: Implement
}
Test 12: isInStock() - False
@Test
@DisplayName("isInStock should return false if stock = 0")
void isInStock_WhenStockZero_ShouldReturnFalse() {
// TODO: Implement
}
Test 13: decreaseStock() - Success
@Test
@DisplayName("decreaseStock should decrease the stock")
void decreaseStock_WithSufficientStock_ShouldDecrease() {
// TODO: Implement
// Verify that the new stock is correct
}
Test 14: decreaseStock() - Insufficient
@Test
@DisplayName("decreaseStock should throw an exception if stock is insufficient")
void decreaseStock_WithInsufficientStock_ShouldThrowException() {
// TODO: Implement
// assertThrows(InsufficientStockException.class, ...)
}
Part 4: Solution
Click to see the complete solution
@ExtendWith(MockitoExtension.class)
class ProductServiceTest {
@Mock
private ProductRepository productRepository;
@InjectMocks
private ProductService productService;
@Captor
private ArgumentCaptor<Product> productCaptor;
private Product sampleProduct;
@BeforeEach
void setUp() {
sampleProduct = new Product(1L, "Laptop", "High-end laptop",
new BigDecimal("999.99"), 10, true);
}
@Test
void findAll_ShouldReturnAllProducts() {
when(productRepository.findAll()).thenReturn(List.of(sampleProduct));
List<Product> result = productService.findAll();
assertThat(result).hasSize(1);
verify(productRepository).findAll();
}
@Test
void findById_WhenExists_ShouldReturnProduct() {
when(productRepository.findById(1L)).thenReturn(Optional.of(sampleProduct));
Product result = productService.findById(1L);
assertThat(result.getName()).isEqualTo("Laptop");
}
@Test
void findById_WhenNotExists_ShouldThrowException() {
when(productRepository.findById(999L)).thenReturn(Optional.empty());
assertThrows(ProductNotFoundException.class,
() -> productService.findById(999L));
}
@Test
void create_WithValidProduct_ShouldSaveAndReturn() {
Product newProduct = new Product(null, "Phone", "Smartphone",
new BigDecimal("599.99"), 5, false);
when(productRepository.save(any())).thenAnswer(inv -> {
Product p = inv.getArgument(0);
p.setId(1L);
return p;
});
Product result = productService.create(newProduct);
assertThat(result.isActive()).isTrue();
verify(productRepository).save(productCaptor.capture());
assertThat(productCaptor.getValue().isActive()).isTrue();
}
@Test
void create_WithEmptyName_ShouldThrowException() {
Product invalid = new Product(null, "", "Desc",
new BigDecimal("100"), 10, true);
assertThrows(IllegalArgumentException.class,
() -> productService.create(invalid));
verify(productRepository, never()).save(any());
}
@Test
void create_WithNegativePrice_ShouldThrowException() {
Product invalid = new Product(null, "Test", "Desc",
new BigDecimal("-10"), 10, true);
assertThrows(IllegalArgumentException.class,
() -> productService.create(invalid));
}
@Test
void delete_WhenExists_ShouldDelete() {
when(productRepository.existsById(1L)).thenReturn(true);
productService.delete(1L);
verify(productRepository).deleteById(1L);
}
@Test
void delete_WhenNotExists_ShouldThrowException() {
when(productRepository.existsById(999L)).thenReturn(false);
assertThrows(ProductNotFoundException.class,
() -> productService.delete(999L));
}
@Test
void deactivate_ShouldSetActiveFalse() {
when(productRepository.findById(1L)).thenReturn(Optional.of(sampleProduct));
productService.deactivate(1L);
verify(productRepository).save(productCaptor.capture());
assertThat(productCaptor.getValue().isActive()).isFalse();
}
@Test
void decreaseStock_WithSufficientStock_ShouldDecrease() {
when(productRepository.findById(1L)).thenReturn(Optional.of(sampleProduct));
productService.decreaseStock(1L, 3);
verify(productRepository).save(productCaptor.capture());
assertThat(productCaptor.getValue().getStock()).isEqualTo(7);
}
@Test
void decreaseStock_WithInsufficientStock_ShouldThrowException() {
sampleProduct.setStock(2);
when(productRepository.findById(1L)).thenReturn(Optional.of(sampleProduct));
assertThrows(InsufficientStockException.class,
() -> productService.decreaseStock(1L, 10));
}
}
Verification
Run the Tests
mvn test -Dtest=ProductServiceTest
Code Coverage
mvn test jacoco:report
# Open target/site/jacoco/index.html
Checklist
- All tests pass (14+ tests)
- ProductService coverage > 80%
- Nominal cases tested
- Error cases tested
- No unnecessary repository calls