I'm trying to do Unit tests on my Spring Boot repository, but my tests will fail and return javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement. I've managed to isolate the problem and it seems to be my data.sql in my resources folder that inhibits my tests from running. It seems that having a prebuilt database creates problems when Spring testing.
Now, I can solve the problem by going into my application.properties file and setting spring.datasource.initialization-mode=always to =never instead. But I would rather be able to only turn off that property while running unit tests.
So my question is if it's possible to ignore the data.sql file or to set spring.datasource.initialization-mode=never within the test class?
Here's my test class below.
@RunWith (SpringRunner.class)
@DataJpaTest
public class BikeRepositoryTest {
@Autowired
TestEntityManager entityManager;
@Autowired
BikeRepository bikeRepo;
@Test
public void testFindAll() {
Bike bike = dummyBike();
entityManager.persist(bike);
entityManager.flush();
List<Bike> bikeList = bikeRepo.findAll();
assertEquals(bikeList.size(), 1);
assertThat(bikeList.contains(bike));
}
public static Bike dummyBike() {
var bike = new Bike();
bike.setName("gustav");
bike.setModel("red_dragon");
bike.setPurchasePrice(BigDecimal.valueOf(456));
return bike;
}
}
Add an application.properties file under src/test/resources and set the test only properties you would like there. Those configurations should override the main configuration when running tests.
I cannot comment on Adam's answer for lack of reputation, but :
In src/test/resources add an application.properties with
spring.sql.init.data-locations=test_data.sql
In src/test/resources add a test_data.sql which cannot be empty for some reason, but a content such as :
SELECT 1 AS DUMMY;
will appease Spring.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With