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