TP9.2 - Testes de Integração dos Repositories
Objetivos do TP
Neste TP, você irá:
- ✅ Testar um repository com @DataJpaTest
- ✅ Utilizar um banco de dados H2 real
- ✅ Testar consultas personalizadas
- ✅ Verificar restrições de unicidade
- ✅ Testar relações entre entidades
Duração estimada: 1h30
Contexto
Você possui as entidades Product e Category com uma relação Many-to-One. Você deve testar se suas consultas JPA funcionam corretamente com um banco de dados real.
Parte 1: As Entidades
Category
@Entity
@Table(name = "categories")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true, nullable = false)
private String name;
private String description;
}
Product
@Entity
@Table(name = "products")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@Column(unique = true)
private String sku;
private BigDecimal price;
private Integer stock;
private boolean active = true;
@ManyToOne
@JoinColumn(name = "category_id")
private Category category;
@Column(name = "created_at")
private LocalDateTime createdAt = LocalDateTime.now();
}
Parte 2: Os Repositories
CategoryRepository
public interface CategoryRepository extends JpaRepository<Category, Long> {
Optional<Category> findByName(String name);
boolean existsByName(String name);
}
ProductRepository
public interface ProductRepository extends JpaRepository<Product, Long> {
// Consultas por propriedade simples
List<Product> findByActiveTrue();
List<Product> findByActiveFalse();
Optional<Product> findBySku(String sku);
// Consultas com critérios
List<Product> findByPriceLessThan(BigDecimal price);
List<Product> findByPriceBetween(BigDecimal min, BigDecimal max);
List<Product> findByStockGreaterThan(Integer stock);
// Consultas com relação
List<Product> findByCategory(Category category);
List<Product> findByCategoryName(String categoryName);
// Consultas com ordenação
List<Product> findByActiveTrueOrderByPriceAsc();
List<Product> findByActiveTrueOrderByCreatedAtDesc();
// Consultas @Query
@Query("SELECT p FROM Product p WHERE p.price < :price AND p.active = true")
List<Product> findCheapActiveProducts(@Param("price") BigDecimal price);
@Query("SELECT COUNT(p) FROM Product p WHERE p.category.id = :categoryId")
long countByCategory(@Param("categoryId") Long categoryId);
@Query("SELECT p FROM Product p WHERE p.stock < :threshold")
List<Product> findLowStockProducts(@Param("threshold") Integer threshold);
}
Parte 3: Configuração de Teste
application-test.properties
# src/test/resources/application-test.properties
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true
Parte 4: Testes a Implementar
Estrutura Básica
@DataJpaTest
@ActiveProfiles("test")
class ProductRepositoryTest {
@Autowired
private ProductRepository productRepository;
@Autowired
private CategoryRepository categoryRepository;
@Autowired
private TestEntityManager entityManager;
private Category electronics;
private Category clothing;
@BeforeEach
void setUp() {
// Criar categorias
electronics = categoryRepository.save(new Category(null, "Electronics", "Electronic devices"));
clothing = categoryRepository.save(new Category(null, "Clothing", "Apparel"));
// Criar produtos
entityManager.persist(new Product(null, "Laptop", "LAP001",
new BigDecimal("999.99"), 10, true, electronics, LocalDateTime.now()));
entityManager.persist(new Product(null, "Phone", "PHO001",
new BigDecimal("599.99"), 25, true, electronics, LocalDateTime.now()));
entityManager.persist(new Product(null, "T-Shirt", "TSH001",
new BigDecimal("29.99"), 100, true, clothing, LocalDateTime.now()));
entityManager.persist(new Product(null, "Old Phone", "PHO002",
new BigDecimal("199.99"), 0, false, electronics, LocalDateTime.now()));
entityManager.flush();
}
}
Teste 1: findAll
@Test
@DisplayName("findAll deve retornar todos os produtos")
void findAll_ShouldReturnAllProducts() {
List<Product> products = productRepository.findAll();
assertThat(products).hasSize(4);
}
Teste 2: findByActiveTrue
@Test
@DisplayName("findByActiveTrue deve retornar apenas os produtos ativos")
void findByActiveTrue_ShouldReturnOnlyActiveProducts() {
// TODO: Implementar
// Esperar 3 produtos ativos
}
Teste 3: findBySku
@Test
@DisplayName("findBySku deve retornar o produto correspondente")
void findBySku_WhenExists_ShouldReturnProduct() {
// TODO: Implementar
}
@Test
@DisplayName("findBySku deve retornar empty quando SKU não existe")
void findBySku_WhenNotExists_ShouldReturnEmpty() {
// TODO: Implementar
}
Teste 4: findByPriceLessThan
@Test
@DisplayName("findByPriceLessThan deve retornar os produtos mais baratos")
void findByPriceLessThan_ShouldReturnCheaperProducts() {
List<Product> products = productRepository.findByPriceLessThan(new BigDecimal("500"));
assertThat(products)
.hasSize(2)
.extracting(Product::getName)
.containsExactlyInAnyOrder("T-Shirt", "Old Phone");
}
Teste 5: findByCategory
@Test
@DisplayName("findByCategory deve retornar os produtos da categoria")
void findByCategory_ShouldReturnProductsInCategory() {
// TODO: Implementar
// Esperar 3 produtos Electronics
}
Teste 6: findByCategoryName
@Test
@DisplayName("findByCategoryName deve retornar os produtos pelo nome da categoria")
void findByCategoryName_ShouldReturnProducts() {
// TODO: Implementar
}
Teste 7: Consulta @Query personalizada
@Test
@DisplayName("findCheapActiveProducts deve retornar os produtos ativos baratos")
void findCheapActiveProducts_ShouldReturnCheapAndActive() {
List<Product> products = productRepository.findCheapActiveProducts(new BigDecimal("100"));
assertThat(products)
.hasSize(1)
.first()
.extracting(Product::getName)
.isEqualTo("T-Shirt");
}
Teste 8: countByCategory
@Test
@DisplayName("countByCategory deve contar os produtos da categoria")
void countByCategory_ShouldReturnCorrectCount() {
// TODO: Implementar
}
Teste 9: findLowStockProducts
@Test
@DisplayName("findLowStockProducts deve retornar os produtos com baixo estoque")
void findLowStockProducts_ShouldReturnLowStock() {
// TODO: Implementar com threshold = 5
}
Teste 10: Teste de restrição de unicidade
@Test
@DisplayName("Deve lançar exceção para SKU duplicado")
void save_WithDuplicateSku_ShouldThrowException() {
Product duplicate = new Product();
duplicate.setName("Duplicate");
duplicate.setSku("LAP001"); // SKU já utilizado
duplicate.setPrice(new BigDecimal("100"));
assertThrows(DataIntegrityViolationException.class, () -> {
productRepository.save(duplicate);
entityManager.flush(); // Força a persistência
});
}
Teste 11: Teste de salvamento com relação
@Test
@DisplayName("Deve salvar um produto com sua categoria")
void save_WithCategory_ShouldPersistRelation() {
Product newProduct = new Product();
newProduct.setName("New Product");
newProduct.setSku("NEW001");
newProduct.setPrice(new BigDecimal("49.99"));
newProduct.setStock(50);
newProduct.setActive(true);
newProduct.setCategory(clothing);
Product saved = productRepository.save(newProduct);
entityManager.flush();
entityManager.clear(); // Limpar o cache
Product found = productRepository.findById(saved.getId()).orElseThrow();
assertThat(found.getCategory()).isNotNull();
assertThat(found.getCategory().getName()).isEqualTo("Clothing");
}
Teste 12: Teste de ordenação
@Test
@DisplayName("findByActiveTrueOrderByPriceAsc deve ordenar por preço crescente")
void findByActiveTrueOrderByPriceAsc_ShouldSortByPrice() {
List<Product> products = productRepository.findByActiveTrueOrderByPriceAsc();
assertThat(products)
.extracting(Product::getPrice)
.isSorted();
}
Parte 5: Gabarito
Clique para ver o gabarito
@DataJpaTest
@ActiveProfiles("test")
class ProductRepositoryTest {
@Autowired
private ProductRepository productRepository;
@Autowired
private CategoryRepository categoryRepository;
@Autowired
private TestEntityManager entityManager;
private Category electronics;
private Category clothing;
@BeforeEach
void setUp() {
electronics = categoryRepository.save(new Category(null, "Electronics", "Electronic devices"));
clothing = categoryRepository.save(new Category(null, "Clothing", "Apparel"));
entityManager.persist(createProduct("Laptop", "LAP001", "999.99", 10, true, electronics));
entityManager.persist(createProduct("Phone", "PHO001", "599.99", 25, true, electronics));
entityManager.persist(createProduct("T-Shirt", "TSH001", "29.99", 100, true, clothing));
entityManager.persist(createProduct("Old Phone", "PHO002", "199.99", 0, false, electronics));
entityManager.flush();
}
private Product createProduct(String name, String sku, String price, int stock, boolean active, Category cat) {
Product p = new Product();
p.setName(name);
p.setSku(sku);
p.setPrice(new BigDecimal(price));
p.setStock(stock);
p.setActive(active);
p.setCategory(cat);
p.setCreatedAt(LocalDateTime.now());
return p;
}
@Test
void findByActiveTrue_ShouldReturnOnlyActiveProducts() {
List<Product> products = productRepository.findByActiveTrue();
assertThat(products).hasSize(3);
assertThat(products).allMatch(Product::isActive);
}
@Test
void findBySku_WhenExists_ShouldReturnProduct() {
Optional<Product> product = productRepository.findBySku("LAP001");
assertThat(product).isPresent();
assertThat(product.get().getName()).isEqualTo("Laptop");
}
@Test
void findByCategory_ShouldReturnProductsInCategory() {
List<Product> products = productRepository.findByCategory(electronics);
assertThat(products).hasSize(3);
}
@Test
void findByCategoryName_ShouldReturnProducts() {
List<Product> products = productRepository.findByCategoryName("Clothing");
assertThat(products).hasSize(1);
assertThat(products.get(0).getName()).isEqualTo("T-Shirt");
}
@Test
void countByCategory_ShouldReturnCorrectCount() {
long count = productRepository.countByCategory(electronics.getId());
assertThat(count).isEqualTo(3);
}
@Test
void findLowStockProducts_ShouldReturnLowStock() {
List<Product> products = productRepository.findLowStockProducts(5);
assertThat(products).hasSize(1);
assertThat(products.get(0).getStock()).isEqualTo(0);
}
}
Verificação
mvn test -Dtest=ProductRepositoryTest
Checklist
- Todos os testes passam
- @DataJpaTest utilizado (não @SpringBootTest)
- TestEntityManager utilizado para o setup
- Consultas personalizadas testadas
- Restrições verificadas