【问题标题】:Initialising a database before Spring Boot test在 Spring Boot 测试之前初始化数据库
【发布时间】:2016-11-10 18:33:21
【问题描述】:

我正在使用 JUnit 测试我的应用程序,只要在测试前初始化数据库(使用 gradle bootRun 作为 web 应用程序运行),一切正常。但是,如果数据库为空,则应用程序似乎不会在测试之前初始化任何模型或实体。有没有办法我应该这样做?我假设ApplicationRunner 类将在测试之前运行并初始化实体。有没有办法做到这一点,还是我使用了错误的方法?

这就是我的application.properties 文件的样子:

server.port=8090
server.ssl.key-store=classpath:keystore.jks
server.ssl.key-store-password=123456
server.ssl.key-password 123456
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.jpa.hibernate.ddl-auto=create
spring.jpa.hibernate.naming-strategy:org.hibernate.cfg.ImprovedNamingStrategy
application.logger.org.springframework=INFO

我的数据库使用DriverManagerDataSource 连接存储在/src/main/java/application/persistence/DbConfig.java 中。我已经设置ApplicationRunner 在启动时向数据库添加几行。

编辑:

我还应该补充一点,这些是我在 JUnit 测试文件中使用的注释:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes={
    AdeyTrackApplication.class, 
    SecurityConfig.class, 
    WebConfig.class,
    AuthorizationController.class
    })

【问题讨论】:

  • 第一种方法是在您的测试类中以setUp 方法初始化数据库。另一种方法是创建测试配置,在其中添加 @PostConstruct 函数,该函数初始化数据库中的数据并将此类添加到 ContextConfiguration
  • @krynio 有没有实现的例子?我对 Spring 不是很有经验,关于 JUnit 也没有遇到过这个注释。
  • 最简单的方法是将 JdbcTemplate 注入你的测试类。接下来您可以使用jdbcTemplate.execue(sql) 执行sql 查询。要在每次测试之前运行此代码,您应该创建带有注释 @BeforesetUp 方法。下面是如何注入 JdbcTemplate 和执行查询的示例:github.com/spring-projects/spring-boot/blob/master/… 和这里是使用 @Before 的示例 junit.sourceforge.net/javadoc/org/junit/Before.html

标签: java mysql spring hibernate spring-boot


【解决方案1】:

如果您不想从 @Before JUnit 钩子中显式执行,有多种选择。

  1. 使用Spring Boot's JDBC initialization feature,将schema.sqldata.sql 放入src/test/resources 文件夹中,以便仅在测试期间提取。
  2. 使用Spring's @Sql annotation

【讨论】:

  • 但是@sql 不能支持每个类只执行一次
【解决方案2】:

您可以使用@Sql 注释来填充您的数据库,例如^

@Sql(scripts = "classpath:db/populateDB.sql")

【讨论】:

    【解决方案3】:

    以上答案都使用 .sql 架构加载技术,我必须有一个 .sql 架构进行测试。我不想那样做,因为我的架构会扩展,而且我不想在我的测试扩展时经历向架构添加条目的麻烦。

    当我使用 Spring Boot 时,我遇到了这个注解,它似乎通过首先运行 bootRun 然后运行测试来解决问题。

    在我的测试注释中,我将@ContextConfigurations 替换为@SpringApplicationConfiguration,并让所有类保持不变。这似乎解决了这个问题。所以现在test 任务调用 bootRun 来加载类并然后运行测试。

    @SpringApplicationConfiguration

    希望这可以帮助任何面临同样问题的人。

    【讨论】:

    • SpringApplicationConfiguration 现已弃用。 as of 1.4 in favor of SpringBootTest or direct use of SpringBootContextLoader
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    • 1970-01-01
    • 1970-01-01
    • 2018-02-14
    • 2019-05-30
    • 2017-07-29
    • 1970-01-01
    相关资源
    最近更新 更多