问题描述
简介: 我们的产品需要对 3 个不同的数据库进行集成测试:
- 甲骨文
- Postgres
- MSsql
我们使用 Spring Boot 作为我们的框架,并使用 TestContainers 来启动上述数据库。
问题: 我们需要为每个容器(数据库)运行相同的测试。
在网上进行了大量挖掘后,我能想到的唯一方法是使用 BaseClass,我们在其中编写所有测试用例和每个容器,我们创建一个继承自 BaseClass 的类,然后覆盖方法和使用@Test 对其进行注释。
在代码下方,您将使用 Postgres 的单个 junit5 扩展,它启动一个 TestContainer、基础测试类和一个从 Postgres 扩展扩展而来的测试类,启动一个 Spring 应用程序上下文,并从基础运行测试班级。
代码:
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 扩展重新运行它而不执行这种多态性?
解决方法
如果您使用的是 maven,您可以尝试为每个 db 设置不同的配置文件