在SpringBootTest中使用其他数据源

问题描述

我正在尝试使用 SpringBootTest 将集成测试添加到我的SpringBoot应用程序中。在生产中,我的应用程序连接到MS SQL Server数据库。对于集成测试,我想使用嵌入式H2 DB,可以在运行所有/每个Int-test之前对架构和数据进行引导。我已经尝试过各种方法,但是无法使其正常工作。以下是当前情况:

在SpringBoot应用程序中-我有一个指向Sql-Server DB的自定义DataSource bean:

@Bean
@Autowired
public DataSource dataSource(SpecificConnectionManager cm) {
    DataSource ds = //Magic with cm to create DataSource
    return ds;
}

对于集成测试,我想使用嵌入式H2数据库来简化工作。为此,我创建了一个测试/开发配置:

spring:
  datasource:
    driverClassName: org.h2.Driver
    password: password
    url: jdbc:h2:mem:csn_seo;MODE=MSSQLServer
    username: sa
  jpa:
    database-platform: org.hibernate.dialect.H2Dialect

在我的集成测试类中,我为SpecificConnectionManager创建了一个MockBean以停止其初始化。我还在测试文件夹中创建了一个新的@Configuration类,以声明另一个要测试的数据源bean:

@Bean
public DataSource getDataSource(){
    DataSourceBuilder dbBuilder = DataSourceBuilder.create();
    return dbBuilder.build();
}

我总是被开头的错误所挫败

没有名为'entityManagerFactory'的bean

我什至尝试在我的test-config类中创建这样的bean。但这会导致(解释)

数据源为空

我的Test类看起来像这样:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@EnableAutoConfiguration(exclude = SecurityAutoConfiguration.class)
@AutoConfigureMockMvc()
@ActiveProfiles("int_test")
@Tag("Integration")
public class MySpecialAppIT {

  @Autowired
  private MockMvc mockMvc;

  @MockBean
  public SpecificConnectionManager sqlConnectionManager;

  @Sql({"classpath:schema.sql","classpath:data.sql"})
  @Test
  public void getAllThingsIT() throws Exception {

    MvcResult result = this.mockMvc
        .perform(get("/things").contentType(MediaType.APPLICATION_JSON)).andDo(print()).andExpect(status().isOk()).andReturn();

    assertNotEqual("",result.getResponse().getContentAsString());
  }
}

非常感谢您的帮助!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...