@DataJpaTest. What is the main behavior of this annotation during test execution?@DataJpaTest sets up a minimal Spring context focused on JPA components. It configures an in-memory database by default, scans for repository interfaces, and disables full auto-configuration like web server startup. This makes repository tests fast and isolated.
@DataJpaTest, what happens to the database state after each test method finishes?By default, @DataJpaTest runs each test method in a transaction that is rolled back after the method completes. This ensures tests do not affect each other and the database state is clean for every test.
UserRepository, which of the following code snippets correctly injects it into a test class annotated with @DataJpaTest?@Autowired is the standard Spring annotation to inject beans in test classes. @Inject and @Resource can work but are less common and may require extra configuration. Direct instantiation does not work because Spring manages the bean lifecycle.
@DataJpaTest tries to inject MyService which depends on UserRepository. The test fails with NoSuchBeanDefinitionException for MyService. Why?@DataJpaTest
class MyServiceTest {
@Autowired
private MyService myService;
}@DataJpaTest configures only JPA repository beans and related database infrastructure. It does not load service or controller beans. To test services, you need a different test annotation or manual bean configuration.
MyCustomBean to the Spring context during a @DataJpaTest. Which approach correctly adds this bean without loading the full application context?Using @Import on a @DataJpaTest class adds the specified bean(s) to the test context without loading the full application. @ComponentScan is too broad and @SpringBootTest loads everything, which is slower. Manual instantiation does not register the bean in Spring context.