【问题标题】:Spring Boot with in memory database fails带有内存数据库的 Spring Boot 失败
【发布时间】:2018-07-17 12:03:10
【问题描述】:

我正在尝试使用嵌入式数据库 h2 测试我的 Spring Boot 应用程序。至于 dev 和 prod,我将使用 MySQL 数据库。

我希望每种模式都有不同的 application.yml 和 schema.sql 文件。

项目结构为:

src
--main
----resources
------application.yml
------schema.sql
--test
----resources
------application-test.yml
------schema-test.sql

这是我的 RespositoryTest :

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@DataJpaTest
public class IUserRepositoryTest {

@Autowired
private TestEntityManager entityManager;

@Autowired
private IUserRepository userRepository;

@Test
public void Should_ReturnEmployee_ForExistingEmail() {
    User oneUser=new User("john","doe","example@email.com");
    entityManager.persist(oneUser);
    List<User> userList=userRepository.findUserByEmail("example@email.com");

    assertThat(userList).isNotEmpty();
    assertThat(userList.get(0)).isNotNull();
    assertThat(userList.get(0).getEmail()).isEqualTo("example@email.com");

}

这是我的测试/资源/application-test.yml:

spring: 
  profiles: test
  datasource:
   url: jdbc:h2:mem:test;INIT=create schema IF NOT EXISTS mydb;DB_CLOSE_DELAY=-1
   platform: h2
   username: sa
   password:
   driverClassName: org.h2.Driver

  jpa:
    hibernate:
      ddl-auto: create-drop
    properties:
      hibernate:
        default-schema: mydb
        dialect: org.hibernate.dialect.H2Dialect

这是我的测试/资源/schema-test.sql:

CREATE SCHEMA IF NOT EXISTS MYDB

至于我的 main/resources/application.yml:

logging:
  level:
    org.springframework.web: DEBUG
    org:
      hibernate:
        SQL: DEBUG


spring:
  jpa:
    hibernate:
      ddl-auto: update
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL5Dialect
  datasource:
    url: jdbc:mysql://localhost:3306/mydb
    username: root
    password: toor
  database:
    driverClassName: com.mysql.jdbc.Driver 

当我将我的应用程序作为 Spring Boot 运行时,使用了主 application.yml 并且一切都很好,但是当我运行我的测试时,我收到了这个错误:

org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL via JDBC Statement

    Caused by: org.h2.jdbc.JdbcSQLException: Schema "MYDB" not found; SQL statement

这导致我所有的测试都失败了。

当我尝试使用这个项目结构时:

src
--main
----resources
------application.yml
------schema.sql
--test
----resources
------application.yml
------schema.sql

测试成功,但是当我将我的应用程序作为 spring boot 运行时,test/resources/application.yml 是正在使用的,而不是主要的。

【问题讨论】:

    标签: spring unit-testing spring-boot junit h2


    【解决方案1】:

    您的测试使用“默认”配置文件运行,因此它只会加载没有后缀的“默认”配置(即 -test)。

    尝试将 @ActiveProfiles("test") 添加到您的测试类以启用测试配置文件。

    【讨论】:

    • 仍然没有运气,同样的错误;我应该将 application-test 放在 main/resources 中吗?
    • 道歉我想我一开始误解了你的问题。尝试分别为您的测试/主模式文件使用 schema-h2.sql 和 schema-mysql.sql。
    • 它似乎工作了,谢谢!工作组合是:schema-h2.sql +application-test.yml + @ActiveProfiles("test") 在我的测试中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-20
    • 2015-06-20
    • 2018-06-02
    • 1970-01-01
    • 2023-03-11
    • 2016-11-14
    相关资源
    最近更新 更多