在Spring中配置用于测试目的的特定内存数据库。
在Spring中配置用于测试目的的特定内存数据库。
如何配置我的Spring Boot应用程序,以便在运行单元测试时使用内存数据库(如H2 / HSQL),但在运行Spring Boot应用程序时使用生产数据库( 如PostgreSQL / MySQL)?
admin 更改状态以发布 2023年5月23日
另一种方法是向测试类添加注释@AutoConfigureTestDatabase
。我的测试通常看起来像这样:
@RunWith(SpringRunner.class) @DataJpaTest @AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.H2) public class MyRepositoryTest { @Autowired MyRepository repository; @Test public void test() throws Exception { // Tests... } }
请注意,需要在pom.xml文件中添加嵌入式数据库依赖项。对于嵌入式数据库,这个注释是不必要的,即使只添加了pom文件中的依赖,它也可以工作。
可以使用Spring配置文件来做到。
首先,需要有特定于环境的属性文件:
application.properties:
spring.profiles.active: dev
application-dev.properties
spring.jpa.database: MYSQL spring.jpa.hibernate.ddl-auto: update spring.datasource.url: jdbc:mysql://localhost:3306/dbname spring.datasource.username: username spring.datasource.password: password
application-test.properties
spring.jpa.database: HSQL
在 pom.xml
中添加 MySQL 和 H2 的驱动器,如下:
mysql mysql-connector-java runtime org.hsqldb hsqldb test
最后,使用 @ActiveProfiles("test")
注释测试类。