You need to enable JavaScript to run this app. JUnit5+Spring Boot+TestContainers多库测试如何避免继承切换扩展
优惠活动
大模型
产品
解决方案
定价
更多

JUnit5+Spring Boot+TestContainers多库测试如何避免继承切换扩展

背景介绍

我们的产品需要针对3种不同数据库编写集成测试,分别为:

  • Oracle
  • Postgres
  • MSSQL

我们采用Spring Boot作为开发框架,使用TestContainers启动上述数据库实例。

问题背景

我们需要为每个数据库容器运行同一套测试用例。
目前的实现方案是:编写存放所有测试用例的基类,为每个数据库容器创建继承自基类的子类,重写基类方法并标注@Test注解。

现有代码示例

Postgres对应的JUnit5扩展(用于启动TestContainer)、测试基类,以及继承Postgres扩展的测试类如下:

import com.company.itest.AutoConfig;
import com.company.itest.BaseIntegrationTest;
import com.company.itest.db.mssql.MSSqlTest;
import com.company.itest.db.oracle.OracleTest;
import com.company.itest.db.postgres.PostgresTest;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

public class TestTheTest extends BaseIntegrationTest {
  public void contextLoads() {
    Assertions.assertEquals(1, 1);
  }
  public void contextLoads2() {
    Assertions.assertNotEquals(1, 2);
  }
}


@SpringBootTest(
    classes = AutoConfig.class,
    webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@PostgresTest
class TestPostgres extends TestTheTest {
  @Test
  public void contextLoads() {
    super.contextLoads();
  }
  @Test
  public void contextLoads2() {
    super.contextLoads2();
  }
}


import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testcontainers.containers.PostgreSQLContainer;

public class PostgresqlTestContainersExtension implements BeforeAllCallback, AfterAllCallback {

  private final Logger log = LoggerFactory.getLogger(PostgresqlTestContainersExtension.class);

  private PostgreSQLContainer<?> postgres;

  @Override
  public void beforeAll(ExtensionContext context) {
    log.info("Setting up postgres container");
    postgres = new PostgreSQLContainer<>("postgres:13").withReuse(true);

    postgres.start();
    System.setProperty("spring.datasource.url", postgres.getJdbcUrl());
    System.setProperty("spring.datasource.username", postgres.getUsername());
    System.setProperty("spring.datasource.password", postgres.getPassword());
  }

  @Override
  public void afterAll(ExtensionContext context) {
    postgres.stop();
  }
}



package com.company.itest.db.postgres;

import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.testcontainers.junit.jupiter.Testcontainers;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Target({TYPE, ANNOTATION_TYPE})
@Retention(RUNTIME)
@ExtendWith(SpringExtension.class)
@ExtendWith({PostgresqlTestContainersExtension.class})
@Testcontainers
public @interface PostgresTest {}

问询问题

无需使用上述多态继承的方案,如何仅创建单个JUnit测试类,即可切换不同JUnit5扩展运行对应数据库的测试?


解决方案

推荐用动态扩展激活+统一配置的方案实现,完全不需要继承多态,仅保留一个测试类即可:

具体实现步骤

  1. 首先把三个数据库的容器启动逻辑合并到同一个JUnit扩展中,通过外部传入的参数决定启动哪一类数据库:
public class MultiDatabaseTestExtension implements BeforeAllCallback, AfterAllCallback {
    private static final Logger log = LoggerFactory.getLogger(MultiDatabaseTestExtension.class);
    private JdbcDatabaseContainer<?> container;

    @Override
    public void beforeAll(ExtensionContext context) {
        // 读取系统参数指定的测试数据库类型,默认启动postgres
        String dbType = System.getProperty("test.db.type", "postgres");
        switch (dbType) {
            case "postgres":
                container = new PostgreSQLContainer<>("postgres:13").withReuse(true);
                break;
            case "oracle":
                container = new OracleContainer("gvenzl/oracle-xe:21-slim").withReuse(true);
                break;
            case "mssql":
                container = new MSSQLServerContainer("mcr.microsoft.com/mssql/server:2022-latest").withReuse(true);
                break;
            default:
                throw new IllegalArgumentException("不支持的数据库类型: " + dbType);
        }
        log.info("启动 {} 测试容器", dbType);
        container.start();
        // 统一注入Spring数据源配置
        System.setProperty("spring.datasource.url", container.getJdbcUrl());
        System.setProperty("spring.datasource.username", container.getUsername());
        System.setProperty("spring.datasource.password", container.getPassword());
        System.setProperty("spring.datasource.driver-class-name", container.getDriverClassName());
    }

    @Override
    public void afterAll(ExtensionContext context) {
        if (container != null && container.isRunning()) {
            container.stop();
        }
    }
}
  1. 自定义统一的集成测试注解,把Spring测试配置、扩展绑定逻辑全部收拢:
@Target({TYPE, ANNOTATION_TYPE})
@Retention(RUNTIME)
@ExtendWith(SpringExtension.class)
@ExtendWith(MultiDatabaseTestExtension.class)
@Testcontainers
@SpringBootTest(
    classes = AutoConfig.class,
    webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT
)
public @interface DatabaseIntegrationTest {}
  1. 仅编写一个测试类,所有测试方法直接标注@Test即可:
@DatabaseIntegrationTest
public class CommonDatabaseIntegrationTest {
  @Test
  public void contextLoads() {
    Assertions.assertEquals(1, 1);
  }
  @Test
  public void contextLoads2() {
    Assertions.assertNotEquals(1, 2);
  }
}

运行方式

执行测试时只需要通过JVM参数指定要测试的数据库类型即可切换:

  • 测试Postgres:mvn test -Dtest.db.type=postgres
  • 测试Oracle:mvn test -Dtest.db.type=oracle
  • 测试MSSQL:mvn test -Dtest.db.type=mssql

如果需要一次执行三个数据库的全部测试,可以配合Maven的多配置执行或者JUnit5的测试套功能,不需要修改测试类代码。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 20:36:05