What is @DataJpaTest and how does it test the repository layer? @DataJpaTest क्या है और यह रिपॉज़िटरी लेयर को कैसे टेस्ट करता है?
@DataJpaTest loads only the JPA-related components — @Entity classes, Spring Data repositories, and the DataSource — without loading services or controllers, giving a focused slice for testing repository queries and entity mappings.
By default it configures an in-memory embedded database (like H2) if available on the classpath and wraps each test in a transaction that's rolled back afterward, keeping tests isolated from each other. It also auto-configures TestEntityManager, a testing-friendly alternative to EntityManager for setting up test data with fine-grained control over flushing.
@DataJpaTest
class UserRepositoryTest {
@Autowired private TestEntityManager entityManager;
@Autowired private UserRepository userRepository;
@Test
void findByEmail_returnsUser() {
entityManager.persist(new User("john@example.com"));
Optional<User> found = userRepository.findByEmail("john@example.com");
assertTrue(found.isPresent());
}
}@DataJpaTest केवल JPA-संबंधित कंपोनेंट्स लोड करता है — @Entity क्लासेज़, स्प्रिंग डेटा रिपॉज़िटरीज़, और DataSource — बिना सर्विसेज़ या कंट्रोलर्स लोड किए, जिससे रिपॉज़िटरी क्वेरीज़ और एंटिटी मैपिंग्स को टेस्ट करने के लिए एक केंद्रित स्लाइस मिलता है।
डिफ़ॉल्ट रूप से यह क्लासपाथ पर उपलब्ध होने पर एक इन-मेमोरी एम्बेडेड डेटाबेस (जैसे H2) कॉन्फिगर करता है और हर टेस्ट को एक ट्रांज़ैक्शन में लपेटता है जिसे बाद में रोलबैक किया जाता है, जिससे टेस्ट एक-दूसरे से अलग रहते हैं।
@DataJpaTest
class UserRepositoryTest {
@Autowired private TestEntityManager entityManager;
@Autowired private UserRepository userRepository;
@Test
void findByEmail_returnsUser() {
entityManager.persist(new User("john@example.com"));
Optional<User> found = userRepository.findByEmail("john@example.com");
assertTrue(found.isPresent());
}
}Was this answer clear?