我正在尝试使用嵌入式数据库 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
测试成功,但是当我将我的应用程序作为弹簧启动运行时,test/resources/application.yml 是正在使用的,而不是主要的。
您的测试使用“默认”配置文件运行,因此它只会加载没有后缀的“默认”配置(即 -test)。
尝试将 @ActiveProfiles("test") 添加到您的测试类以启用测试配置文件。