【问题标题】:H2 db for SpringBoot tests用于 Spring Boot 测试的 H2 db
【发布时间】:2018-02-05 13:29:09
【问题描述】:

我正在使用 Postgres 数据库,我想使用 H2 数据库进行测试。问题是当我在数据库中创建新对象时,测试中似乎根本没有使用 H2。

测试类:

 @RunWith(SpringJUnit4ClassRunner.class)
 @SpringBootTest
 @AutoConfigureMockMvc
 @WithMockUser(roles = "ADMIN")
 @ActiveProfiles("test")
 public class CompanyTests {

@SpyBean
private CompanyService companyServiceMock;

@Autowired
private MockMvc mockMvc;

@Autowired
EntityManager entityManager;

@Test
@Transactional
public void testaaaa() {
    entityManager.persist(new Company("nnnn", new Address()));
    List<Company> all = companyServiceMock.findAll();
    all.forEach(company -> System.out.println(company.getName()));
}

application.properties:

 spring.datasource.driverClassName=org.postgresql.Driver
 spring.datasource.url=jdbc:postgresql://localhost:5432/EDI
 spring.datasource.username=postgres
 spring.datasource.password=password
 spring.datasource.platform=postgresql
 spring.datasource.initialize=true
 spring.datasource.continue-on-error=true
 spring.jackson.serialization.fail-on-empty-beans=false

 spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
 spring.jpa.generate-ddl=true
 spring.jpa.show-sql=true
 spring.jpa.hibernate.ddl-auto=create

应用程序测试属性:

spring.datasource.initialize=true
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-        
1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.h2.console.enabled=true

当我在测试中使用 findAll() 时,它会列出所有来自 postgresql 的公司和由 entityManager 创建的 new。

【问题讨论】:

    标签: java spring testing spring-boot h2


    【解决方案1】:

    您应该为devtest 配置文件分别设置属性文件,在您的情况下,您应该将application.properties 重命名为application-dev.properties 并创建只有一个属性application.propertiesapplication.properties 文件spring.profiles.active=dev

    【讨论】:

    • 我之前试过了,还是一样。 :( 在 application.properties 中我必须有 spring.queries.users 和 spring.queries.roles,但我认为在这种情况下并不重要
    • 您的pom.xml 中是否有配置文件部分,每个配置文件都有适当的依赖关系?
    • 当我将依赖项添加到配置文件时,项目中到处都是“无法解决”。 ://
    【解决方案2】:

    在注解中添加@TestPropertySource(locations= "classpath:application-test.properties") 怎么样?您应该明确说明您正在使用测试 application.properties 的测试类。

    这有点晚了,但我很乐意为您提供帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-16
      • 2018-10-24
      • 2020-10-23
      • 2017-02-03
      • 2019-04-01
      • 2022-01-09
      • 2011-12-31
      • 1970-01-01
      相关资源
      最近更新 更多