代码之家  ›  专栏  ›  技术社区  ›  maxorcist

弹簧启动忽略数据.sql运行单元测试时

  •  2
  • maxorcist  · 技术社区  · 7 年前

    我试图在我的Spring Boot存储库上进行单元测试,但是我的测试将失败并返回 javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement data.sql 在“我的资源”文件夹中,禁止运行测试。在Spring测试时,似乎有一个预构建的数据库会产生问题。

    现在,我可以通过进入我的生活来解决这个问题 application.properties spring.datasource.initialization-mode=always =never 相反。但我宁愿只能在运行单元测试时关闭该属性。

    所以我的问题是,是否有可能忽略 数据.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;
    }   
    }
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Adam    7 年前

    添加 application.properties src/test/resources 并在此处设置只测试的属性。运行测试时,这些配置应该覆盖主配置。