运行单元测试时,Spring Boot忽略data.sql [英] Spring Boot ignore data.sql when running unit tests

查看:115
本文介绍了运行单元测试时,Spring Boot忽略data.sql的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Spring Boot存储库上进行单元测试,但是我的测试将失败并返回 javax.persistence.PersistenceException:org.hibernate.exception.ConstraintViolationException:无法执行语句.我已经设法解决了这个问题,并且似乎是我的 data.sql 在我的resources文件夹中阻止了我的测试运行.在春季测试时,拥有一个预先构建的数据库似乎会产生问题.

现在,我可以通过进入我的 application.properties 文件并将 spring.datasource.initialization-mode = always 设置为 = never .但是我宁愿只能在运行单元测试时关闭该属性.

所以我的问题是是否可以忽略 data.sql 文件或在测试类中设置 spring.datasource.initialization-mode = never ?>

这是我下面的测试课.

  @RunWith(SpringRunner.class)@DataJpaTest公共类BikeRepositoryTest {@AutowiredTestEntityManager实体管理器;@AutowiredBikeRepository bikeRepo;@测试公共无效testFindAll(){自行车= dummyBike();entityManager.persist(bike);entityManager.flush();List< Bike>bikeList = bikeRepo.findAll();assertEquals(bikeList.size(),1);assertThat(bikeList.contains(bike));}公共静态Bike dummyBike(){var bike = new Bike();bike.setName("gustav");bike.setModel("red_dragon");bike.setPurchasePrice(BigDecimal.valueOf(456));归还自行车;}} 

解决方案

src/test/resources 下添加 application.properties 文件,并设置仅测试属性想在那里.在运行测试时,这些配置应优先于主要配置.

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

解决方案

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.

这篇关于运行单元测试时,Spring Boot忽略data.sql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆