Aller au contenu principal

TP9.1 - Tests Unitaires du Service Layer

Objectifs du TP​

Dans ce TP, vous allez:

  1. ✅ Tester un ProductService complet avec Mockito
  2. ✅ Couvrir les cas nominaux et d'erreur
  3. ✅ Utiliser @Mock et @InjectMocks
  4. ✅ Vérifier les interactions avec verify()
  5. ✅ Atteindre une couverture de code élevée

Durée estimée: 1h30


Contexte​

Vous avez un ProductService qui gère les produits d'un e-commerce. Vous devez tester toutes ses méthodes sans utiliser de base de données.


Partie 1: Le Code à Tester​

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);
}
}

Partie 2: Créer la Classe de Test​

Structure de Base​

@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);
}
}

Partie 3: Tests à Implémenter​

Test 1: findAll()​

@Test
@DisplayName("findAll devrait retourner tous les produits")
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() - Succès​

@Test
@DisplayName("findById devrait retourner le produit quand il existe")
void findById_WhenExists_ShouldReturnProduct() {
// TODO: Implémenter
// Hint: when(...).thenReturn(Optional.of(...))
}

Test 3: findById() - Not Found​

@Test
@DisplayName("findById devrait lever une exception quand le produit n'existe pas")
void findById_WhenNotExists_ShouldThrowException() {
// TODO: Implémenter
// Hint: when(...).thenReturn(Optional.empty())
// assertThrows(ProductNotFoundException.class, ...)
}

Test 4: create() - Succès​

@Test
@DisplayName("create devrait sauvegarder et retourner le produit")
void create_WithValidProduct_ShouldSaveAndReturn() {
// TODO: Implémenter
// Vérifier que le produit est marqué actif
// Vérifier que save() est appelé
}

Test 5: create() - Validation Name​

@Test
@DisplayName("create devrait lever une exception si le nom est vide")
void create_WithEmptyName_ShouldThrowException() {
// TODO: Implémenter
// assertThrows(IllegalArgumentException.class, ...)
// verify(productRepository, never()).save(any())
}

Test 6: create() - Validation Price​

@Test
@DisplayName("create devrait lever une exception si le prix est négatif")
void create_WithNegativePrice_ShouldThrowException() {
// TODO: Implémenter
}

Test 7: update()​

@Test
@DisplayName("update devrait modifier et sauvegarder le produit")
void update_ShouldModifyAndSave() {
// TODO: Implémenter
// Vérifier que les champs sont mis à jour
}

Test 8: delete() - Succès​

@Test
@DisplayName("delete devrait supprimer le produit existant")
void delete_WhenExists_ShouldDelete() {
// TODO: Implémenter
// when(existsById).thenReturn(true)
// verify deleteById
}

Test 9: delete() - Not Found​

@Test
@DisplayName("delete devrait lever une exception si le produit n'existe pas")
void delete_WhenNotExists_ShouldThrowException() {
// TODO: Implémenter
}

Test 10: deactivate()​

@Test
@DisplayName("deactivate devrait mettre active à false")
void deactivate_ShouldSetActiveFalse() {
// TODO: Implémenter
// Utiliser ArgumentCaptor pour vérifier la valeur sauvegardée
}

Test 11: isInStock() - True​

@Test
@DisplayName("isInStock devrait retourner true si stock > 0")
void isInStock_WhenStockPositive_ShouldReturnTrue() {
// TODO: Implémenter
}

Test 12: isInStock() - False​

@Test
@DisplayName("isInStock devrait retourner false si stock = 0")
void isInStock_WhenStockZero_ShouldReturnFalse() {
// TODO: Implémenter
}

Test 13: decreaseStock() - Succès​

@Test
@DisplayName("decreaseStock devrait diminuer le stock")
void decreaseStock_WithSufficientStock_ShouldDecrease() {
// TODO: Implémenter
// Vérifier que le nouveau stock est correct
}

Test 14: decreaseStock() - Insufficient​

@Test
@DisplayName("decreaseStock devrait lever une exception si stock insuffisant")
void decreaseStock_WithInsufficientStock_ShouldThrowException() {
// TODO: Implémenter
// assertThrows(InsufficientStockException.class, ...)
}

Partie 4: Solutionnaire​

Cliquer pour voir le solutionnaire complet
@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));
}
}

Vérification​

Exécuter les Tests​

mvn test -Dtest=ProductServiceTest

Couverture de Code​

mvn test jacoco:report
# Ouvrir target/site/jacoco/index.html

Checklist​

  • Tous les tests passent (14+ tests)
  • Couverture ProductService > 80%
  • Cas nominaux testés
  • Cas d'erreur testés
  • Pas d'appels inutiles au repository

🎯 Prochaine Étape​

➡️ TP9.2: Tests d'Intégration


⬅️ Retour au Module 9