内存中数据库的Spring引导失败
我正试图用嵌入式数据库h2测试我的Spring Boot应用程序。至于dev和prod,我将使用MySQL数据库 我希望每个模式都有不同的application.yml和schema.sql文件 项目结构为:内存中数据库的Spring引导失败,spring,unit-testing,spring-boot,junit,h2,Spring,Unit Testing,Spring Boot,Junit,H2,我正试图用嵌入式数据库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 这是我的回答测试:
src
--main
----resources
------application.yml
------schema.sql
--test
----resources
------application-test.yml
------schema-test.sql
这是我的回答测试:
@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");
}
这是我的test/resources/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应用程序运行我的应用程序时,会使用main 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启动方式运行我的应用程序时,使用的是test/resources/application.yml,而不是主文件。您的测试使用默认配置文件运行,因此它将只加载没有后缀的默认配置,即-test
尝试将@ActiveProfilestest添加到您的测试类以启用测试配置文件。仍然不走运,同样的错误;我应该把应用程序测试放在main/resources中吗?抱歉,我想我一开始误解了你的问题。尝试分别使用schema-h2.sql和schema-mysql.sql作为您的测试/主模式文件。它似乎可以工作,谢谢!在我的测试中,工作组合是:schema-h2.sql+application-test.yml+@ActiveProfilestest。
src
--main
----resources
------application.yml
------schema.sql
--test
----resources
------application.yml
------schema.sql