Reputation: 369
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;
}
}
Upvotes: 4
Views: 4274
Reputation: 728
As of 2023 and for Spring Boot 3.1.0 the name of the property is spring.sql.init.mode
. Setting it to never
in an application.properties file under test/resources will disable initialization as long as you are running the tests under the default profile (otherwise, set that property on the correct profile). This is because, as other answers have stated, the properties under the test folder will override those under main.
This property can take three values, default being embedded
and the other two always
and never
. Default value will only initialize the database if an embedded database is used (e.g. H2), and always
will , of course, initialize the database under any circumstances.
Upvotes: 0
Reputation: 41
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.
Upvotes: 1
Reputation: 2269
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.
Upvotes: 3