You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 2.3.0+中@MockBean模拟DataSource Bean失败问题

Spring Boot 2.3.0+版本中@MockBean模拟DataSource测试失败问题

在Spring Boot 2.3.0.RELEASE及更高版本中,使用@MockBean注解模拟javax.sql.DataSource的测试用例无法正常启动,抛出如下错误:

Caused by: org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection: DataSource returned null from getConnection(): javax.sql.DataSource#0 bean

但切换到2.2.13.RELEASE等旧版本时,测试可以正常运行。

相关代码

测试类代码

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {pService.class})
@Import({
    JdbcConfiguration.class
})
class DataMockTestApplicationTests {

    @MockBean
    private DataSource dataSource;

    @Test
    void contextLoads() {
        assertTrue(true);
    }

}

配置类代码

@Configuration
public class JdbcConfiguration extends AbstractJdbcConfiguration {
  @Value("${f.jdbc.url}")
  private String fUrl;

  @Value("${f.jdbc.username}")
  private String fUsername;

  @Value("${f.jdbc.password}")
  private String fPassword;

  @Bean
  NamedParameterJdbcOperations operations(DataSource dataSource) {
    return new NamedParameterJdbcTemplate(dataSource);
  }

  @Bean(name = "fOperations")
  NamedParameterJdbcOperations fOperations() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
    dataSource.setUrl(fUrl);
    dataSource.setUsername(fUsername);
    dataSource.setPassword(fPassword);
    return new NamedParameterJdbcTemplate(dataSource);
  }
}

服务类代码

@Component
@Qualifier("pService")
public class pService {
}

build.gradle配置

plugins {
    id 'java'
    id 'org.springframework.boot' version '2.3.0.RELEASE'    // -------> 1
    //id 'org.springframework.boot' version '2.2.13.RELEASE'     //  -------> 2
    id 'io.spring.dependency-management' version '1.0.9.RELEASE'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jdbc'
    runtimeOnly 'mysql:mysql-connector-java'
    testImplementation 'junit:junit'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

tasks.named('test') {
    useJUnitPlatform()
}

取消注释第2行并注释第1行,使用2.2.13.RELEASE版本时测试可正常运行。

内容的提问来源于stack exchange,提问作者Rajeev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 01:28:35