Skip to main content

TP9.2 - Integration Tests of Repositories

Objectives of the Lab​

In this lab, you will:

  1. ✅ Test a repository with @DataJpaTest
  2. ✅ Use a real H2 database
  3. ✅ Test custom queries
  4. ✅ Verify uniqueness constraints
  5. ✅ Test relationships between entities

Estimated duration: 1h30


Context​

You have Product and Category entities with a Many-to-One relationship. You need to test that your JPA queries work correctly with a real database.


Part 1: The Entities​

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

Part 2: The 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> {

// Queries by simple property
List<Product> findByActiveTrue();
List<Product> findByActiveFalse();
Optional<Product> findBySku(String sku);

// Queries with criteria
List<Product> findByPriceLessThan(BigDecimal price);
List<Product> findByPriceBetween(BigDecimal min, BigDecimal max);
List<Product> findByStockGreaterThan(Integer stock);

// Queries with relationship
List<Product> findByCategory(Category category);
List<Product> findByCategoryName(String categoryName);

// Queries with sorting
List<Product> findByActiveTrueOrderByPriceAsc();
List<Product> findByActiveTrueOrderByCreatedAtDesc();

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

Part 3: Test Configuration​

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

Part 4: Tests to Implement​

Basic Structure​

@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() {
// Create categories
electronics = categoryRepository.save(new Category(null, "Electronics", "Electronic devices"));
clothing = categoryRepository.save(new Category(null, "Clothing", "Apparel"));

// Create products
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();
}
}

Test 1: findAll​

@Test
@DisplayName("findAll should return all products")
void findAll_ShouldReturnAllProducts() {
List<Product> products = productRepository.findAll();

assertThat(products).hasSize(4);
}

Test 2: findByActiveTrue​

@Test
@DisplayName("findByActiveTrue should return only active products")
void findByActiveTrue_ShouldReturnOnlyActiveProducts() {
// TODO: Implement
// Expect 3 active products
}

Test 3: findBySku​

@Test
@DisplayName("findBySku should return the corresponding product")
void findBySku_WhenExists_ShouldReturnProduct() {
// TODO: Implement
}

@Test
@DisplayName("findBySku should return empty when SKU does not exist")
void findBySku_WhenNotExists_ShouldReturnEmpty() {
// TODO: Implement
}

Test 4: findByPriceLessThan​

@Test
@DisplayName("findByPriceLessThan should return cheaper products")
void findByPriceLessThan_ShouldReturnCheaperProducts() {
List<Product> products = productRepository.findByPriceLessThan(new BigDecimal("500"));

assertThat(products)
.hasSize(2)
.extracting(Product::getName)
.containsExactlyInAnyOrder("T-Shirt", "Old Phone");
}

Test 5: findByCategory​

@Test
@DisplayName("findByCategory should return products in the category")
void findByCategory_ShouldReturnProductsInCategory() {
// TODO: Implement
// Expect 3 Electronics products
}

Test 6: findByCategoryName​

@Test
@DisplayName("findByCategoryName should return products by category name")
void findByCategoryName_ShouldReturnProducts() {
// TODO: Implement
}

Test 7: Custom @Query​

@Test
@DisplayName("findCheapActiveProducts should return cheap and active products")
void findCheapActiveProducts_ShouldReturnCheapAndActive() {
List<Product> products = productRepository.findCheapActiveProducts(new BigDecimal("100"));

assertThat(products)
.hasSize(1)
.first()
.extracting(Product::getName)
.isEqualTo("T-Shirt");
}

Test 8: countByCategory​

@Test
@DisplayName("countByCategory should count the products in the category")
void countByCategory_ShouldReturnCorrectCount() {
// TODO: Implement
}

Test 9: findLowStockProducts​

@Test
@DisplayName("findLowStockProducts should return products with low stock")
void findLowStockProducts_ShouldReturnLowStock() {
// TODO: Implement with threshold = 5
}

Test 10: Uniqueness Constraint Test​

@Test
@DisplayName("Should throw an exception for a duplicate SKU")
void save_WithDuplicateSku_ShouldThrowException() {
Product duplicate = new Product();
duplicate.setName("Duplicate");
duplicate.setSku("LAP001"); // SKU already used
duplicate.setPrice(new BigDecimal("100"));

assertThrows(DataIntegrityViolationException.class, () -> {
productRepository.save(duplicate);
entityManager.flush(); // Force persistence
});
}

Test 11: Save with Relationship Test​

@Test
@DisplayName("Should save a product with its category")
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(); // Clear cache

Product found = productRepository.findById(saved.getId()).orElseThrow();

assertThat(found.getCategory()).isNotNull();
assertThat(found.getCategory().getName()).isEqualTo("Clothing");
}

Test 12: Sorting Test​

@Test
@DisplayName("findByActiveTrueOrderByPriceAsc should sort by ascending price")
void findByActiveTrueOrderByPriceAsc_ShouldSortByPrice() {
List<Product> products = productRepository.findByActiveTrueOrderByPriceAsc();

assertThat(products)
.extracting(Product::getPrice)
.isSorted();
}

Part 5: Solution​

Click to see the solution
@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);
}
}

Verification​

mvn test -Dtest=ProductRepositoryTest

Checklist​

  • All tests pass
  • @DataJpaTest used (not @SpringBootTest)
  • TestEntityManager used for setup
  • Custom queries tested
  • Constraints verified

🎯 Next Step​

➡️ TP9.3: REST API Tests


⬅️ Back to Module 9