Issue
I have this test in my project:
@DataJpaTest
@SpringBootTest
@TestPropertySource(locations = "classpath:local-configuration.properties")
public class CanPixaRepositoryTest {
@Autowired
private CanPixaRepository canPixaRepository;
public void setUp() throws Exception {
}
@Test
public void testAll() {
canPixaRepository].getAvui("fqs");
}
}
local-configuration.properties:
spring.datasource.url=jdbc:h2:mem:testdb;MODE=MySQL;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=sa
spring.datasource.password=
but when I run the test, canPixaRepositoryRepository is null
Solution
For Spring boot applications, the simplest approach is using @DataJpaTest with H2 to test your repositories if you are using JPA and Spring Data JPA.
- Add h2 dependency into your test scope. Spring Boot will auto-configure it and use it to replace the runtime DataSource in the testing phase.
- Annotate your tests with
@DataJpaTest
. Then theEntityManager
, your repositories, and a test-purposeTestEntityManager
are available in the Spring Application Context.
Check my example here.
(Spring 5/Spring Boot 2 added Junit 5 support, it does not require the @Runwith
or @Extendwith
if you are using Junit 5 integration, the DataJpaTest itself is a meta-annotation, before Spring 2.4, to enable Junit5, you have to exclude JUnit 4 from spring-boot-test and add JUnit 5 manually. In the upcoming Spring Boot 2.4, JUnit 5 is the default test runner)
Answered By - Hantsy
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)