首页 > 解决方案 > 如何在测试中提高 H2 碱基

问题描述

该项目使用 H2 数据库。如果你只是运行 Spring,那么一切正常,我从浏览器连接到它。但是如果我在调试模式下运行一次迭代测试,我就无法连接到数据库。如何打败它?这是。文件 pom.xml

<dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
   <version>1.4.200</version>
</dependency>

应用程序属性

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=create
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
# H2 settings
spring.h2.console.enabled=true
spring.h2.console.path=/h2
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

这是一个测试的例子。我在 debag 模式下运行它。

@SpringBootTest
public class UserServiseTest {
  User user;
  @Autowired
  UserService userService;
  @DisplayName("Test write DB")
  @Test
  public void writeData() {
    user = new User(1, 35);
    userService.save(user);
    //here I put a stop point
    user = new User(1, 25);
    userService.save(user);
    user = new User(1, 45);
    userService.save(user);
  }
}

也许有人有一个工作示例,该数据库在测试中工作?我从浏览器连接

http://localhost:8080/h2

事实是数据被写入数据库。我在测试中添加了一个方法

userService.getId(1);

并获得了第一个用户对象 (1, 35) 即一切正常,我只是无法从浏览器连接到数据库。只有在测试模式下,如果我运行常规的 Spring 应用程序,我的数据库会在浏览器中的同一地址安全地打开。

标签: spring-booth2

解决方案


推荐阅读