spring-boot - Spring Boot 在运行单元测试时忽略 data.sql

标签 spring-boot junit

我正在尝试对我的 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/

相关文章:

java - Tomee maven 安装目标发送 : Could not initialize class org. apache.openejb.util.JuliLogStreamFactory

java - AspectJ + Junit + Maven - 在测试中识别切入点但 NoSuchMethodError : aspectOf() exception thrown

java - 在 Vaadin 23 + Spring Security + Azure AD 中访问 Microsoft Graph API

java - Spring 交易级别范围

spring-boot - 从命令行运行时如何将 JVM 参数添加到 Spring boot?

java - 响应返回给客户端后清理

unit-testing - 如何使 Mock 对象与目标对象保持同步

java - Spring Boot 在模块化 Java 中配置 DevTools

java - Junit4 测试 JsonSyntaxException 失败

java - Ant 和 Junit 测试 java.lang.ClassNotFoundException