我正在尝试对我的 Spring Boot 存储库进行单元测试,但我的测试将失败并返回 javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
。我已经设法找出问题所在,它似乎是我的资源文件夹中的 data.sql
阻止了我的测试运行。似乎预建数据库会在 Spring 测试时产生问题。
现在,我可以通过进入我的 application.properties
文件并将 spring.datasource.initialization-mode=always
设置为 =never< 来解决这个问题
代替。但我宁愿只能在运行单元测试时关闭该属性。
所以我的问题是,是否可以忽略 data.sql
文件或在测试类中设置 spring.datasource.initialization-mode=never
?
下面是我的测试类。
@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;
}
}
最佳答案
在 src/test/resources
下添加一个 application.properties
文件,并在那里设置您想要的仅测试属性。在运行测试时,这些配置应该覆盖主配置。
关于spring-boot - Spring Boot 在运行单元测试时忽略 data.sql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52092519/