Pular para o conteúdo principal

TP9.1 - Testes Unitários do Service Layer

Objetivos do TP​

Neste TP, você irá:

  1. ✅ Testar um ProductService completo com Mockito
  2. ✅ Cobrir os casos de sucesso e erro
  3. ✅ Utilizar @Mock e @InjectMocks
  4. ✅ Verificar as interações com verify()
  5. ✅ Alcançar alta cobertura de código

Duração estimada: 1h30


Contexto​

Você tem um ProductService que gerencia os produtos de um e-commerce. Você deve testar todos os seus métodos sem utilizar um banco de dados.


Parte 1: O Código a Ser Testado​

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: Criar a Classe de Teste​

Estrutura 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: Testes a Implementar​

Teste 1: findAll()​

@Test
@DisplayName("findAll deve retornar todos os produtos")
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();
}

Teste 2: findById() - Sucesso​

@Test
@DisplayName("findById deve retornar o produto quando ele existe")
void findById_WhenExists_ShouldReturnProduct() {
// TODO: Implementar
// Hint: when(...).thenReturn(Optional.of(...))
}

Teste 3: findById() - Não Encontrado​

@Test
@DisplayName("findById deve lançar uma exceção quando o produto não existe")
void findById_WhenNotExists_ShouldThrowException() {
// TODO: Implementar
// Hint: when(...).thenReturn(Optional.empty())
// assertThrows(ProductNotFoundException.class, ...)
}

Teste 4: create() - Sucesso​

@Test
@DisplayName("create deve salvar e retornar o produto")
void create_WithValidProduct_ShouldSaveAndReturn() {
// TODO: Implementar
// Verificar se o produto está marcado como ativo
// Verificar se save() foi chamado
}

Teste 5: create() - Validação Nome​

@Test
@DisplayName("create deve lançar uma exceção se o nome estiver vazio")
void create_WithEmptyName_ShouldThrowException() {
// TODO: Implementar
// assertThrows(IllegalArgumentException.class, ...)
// verify(productRepository, never()).save(any())
}

Teste 6: create() - Validação Preço​

@Test
@DisplayName("create deve lançar uma exceção se o preço for negativo")
void create_WithNegativePrice_ShouldThrowException() {
// TODO: Implementar
}

Teste 7: update()​

@Test
@DisplayName("update deve modificar e salvar o produto")
void update_ShouldModifyAndSave() {
// TODO: Implementar
// Verificar se os campos foram atualizados
}

Teste 8: delete() - Sucesso​

@Test
@DisplayName("delete deve remover o produto existente")
void delete_WhenExists_ShouldDelete() {
// TODO: Implementar
// when(existsById).thenReturn(true)
// verify deleteById
}

Teste 9: delete() - Não Encontrado​

@Test
@DisplayName("delete deve lançar uma exceção se o produto não existir")
void delete_WhenNotExists_ShouldThrowException() {
// TODO: Implementar
}

Teste 10: deactivate()​

@Test
@DisplayName("deactivate deve definir active como false")
void deactivate_ShouldSetActiveFalse() {
// TODO: Implementar
// Usar ArgumentCaptor para verificar o valor salvo
}

Teste 11: isInStock() - True​

@Test
@DisplayName("isInStock deve retornar true se stock > 0")
void isInStock_WhenStockPositive_ShouldReturnTrue() {
// TODO: Implementar
}

Teste 12: isInStock() - False​

@Test
@DisplayName("isInStock deve retornar false se stock = 0")
void isInStock_WhenStockZero_ShouldReturnFalse() {
// TODO: Implementar
}

Teste 13: decreaseStock() - Sucesso​

@Test
@DisplayName("decreaseStock deve diminuir o estoque")
void decreaseStock_WithSufficientStock_ShouldDecrease() {
// TODO: Implementar
// Verificar se o novo estoque está correto
}

Teste 14: decreaseStock() - Insuficiente​

@Test
@DisplayName("decreaseStock deve lançar uma exceção se o estoque for insuficiente")
void decreaseStock_WithInsufficientStock_ShouldThrowException() {
// TODO: Implementar
// assertThrows(InsufficientStockException.class, ...)
}

Parte 4: Gabarito​

Clique para ver o gabarito 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));
}
}

Verificação​

Executar os Testes​

mvn test -Dtest=ProductServiceTest

Cobertura de Código​

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

Checklist​

  • Todos os testes passam (14+ testes)
  • Cobertura ProductService > 80%
  • Casos de sucesso testados
  • Casos de erro testados
  • Sem chamadas desnecessárias ao repository

🎯 Próxima Etapa​

➡️ TP9.2: Testes de Integração


⬅️ Voltar ao Módulo 9