TP9.1 - Tests Unitarios del Service Layer
Objetivos del TP
En este TP, usted va a:
- ✅ Probar un ProductService completo con Mockito
- ✅ Cubrir los casos nominales y de error
- ✅ Utilizar @Mock y @InjectMocks
- ✅ Verificar las interacciones con verify()
- ✅ Alcanzar una alta cobertura de código
Duración estimada: 1h30
Contexto
Usted tiene un ProductService que gestiona los productos de un e-commerce. Debe probar todos sus métodos sin utilizar una base de datos.
Parte 1: El Código a Probar
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);
}
}
Parte 2: Crear la Clase de Prueba
Estructura Básica
@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);
}
}
Parte 3: Pruebas a Implementar
Test 1: findAll()
@Test
@DisplayName("findAll debería retornar todos los productos")
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() - Éxito
@Test
@DisplayName("findById debería retornar el producto cuando existe")
void findById_WhenExists_ShouldReturnProduct() {
// TODO: Implementar
// Hint: when(...).thenReturn(Optional.of(...))
}
Test 3: findById() - No Encontrado
@Test
@DisplayName("findById debería lanzar una excepción cuando el producto no existe")
void findById_WhenNotExists_ShouldThrowException() {
// TODO: Implementar
// Hint: when(...).thenReturn(Optional.empty())
// assertThrows(ProductNotFoundException.class, ...)
}
Test 4: create() - Éxito
@Test
@DisplayName("create debería guardar y retornar el producto")
void create_WithValidProduct_ShouldSaveAndReturn() {
// TODO: Implementar
// Verificar que el producto está marcado como activo
// Verificar que save() es llamado
}
Test 5: create() - Validación Nombre
@Test
@DisplayName("create debería lanzar una excepción si el nombre está vacío")
void create_WithEmptyName_ShouldThrowException() {
// TODO: Implementar
// assertThrows(IllegalArgumentException.class, ...)
// verify(productRepository, never()).save(any())
}
Test 6: create() - Validación Precio
@Test
@DisplayName("create debería lanzar una excepción si el precio es negativo")
void create_WithNegativePrice_ShouldThrowException() {
// TODO: Implementar
}
Test 7: update()
@Test
@DisplayName("update debería modificar y guardar el producto")
void update_ShouldModifyAndSave() {
// TODO: Implementar
// Verificar que los campos son actualizados
}
Test 8: delete() - Éxito
@Test
@DisplayName("delete debería eliminar el producto existente")
void delete_WhenExists_ShouldDelete() {
// TODO: Implementar
// when(existsById).thenReturn(true)
// verify deleteById
}
Test 9: delete() - No Encontrado
@Test
@DisplayName("delete debería lanzar una excepción si el producto no existe")
void delete_WhenNotExists_ShouldThrowException() {
// TODO: Implementar
}
Test 10: deactivate()
@Test
@DisplayName("deactivate debería poner active en false")
void deactivate_ShouldSetActiveFalse() {
// TODO: Implementar
// Utilizar ArgumentCaptor para verificar el valor guardado
}
Test 11: isInStock() - Verdadero
@Test
@DisplayName("isInStock debería retornar true si stock > 0")
void isInStock_WhenStockPositive_ShouldReturnTrue() {
// TODO: Implementar
}
Test 12: isInStock() - Falso
@Test
@DisplayName("isInStock debería retornar false si stock = 0")
void isInStock_WhenStockZero_ShouldReturnFalse() {
// TODO: Implementar
}
Test 13: decreaseStock() - Éxito
@Test
@DisplayName("decreaseStock debería disminuir el stock")
void decreaseStock_WithSufficientStock_ShouldDecrease() {
// TODO: Implementar
// Verificar que el nuevo stock es correcto
}
Test 14: decreaseStock() - Insuficiente
@Test
@DisplayName("decreaseStock debería lanzar una excepción si el stock es insuficiente")
void decreaseStock_WithInsufficientStock_ShouldThrowException() {
// TODO: Implementar
// assertThrows(InsufficientStockException.class, ...)
}
Parte 4: Solucionario
Haga clic para ver el solucionario completo
@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));
}
}
Verificación
Ejecutar las Pruebas
mvn test -Dtest=ProductServiceTest
Cobertura de Código
mvn test jacoco:report
# Abrir target/site/jacoco/index.html
Checklist
- Todas las pruebas pasan (14+ pruebas)
- Cobertura ProductService > 80%
- Casos nominales probados
- Casos de error probados
- Sin llamadas innecesarias al repository
🎯 Siguiente Paso
➡️ TP9.2: Pruebas de Integración