当不使用Spring的情况下使用Testcontainers,可以按照以下步骤进行解决:
org.testcontainers
testcontainers
1.16.0
test
org.testcontainers
postgresql
1.16.0
test
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.utility.DockerImageName;
public class MyTest {
private static PostgreSQLContainer> postgresContainer;
@BeforeAll
public static void setup() {
postgresContainer = new PostgreSQLContainer<>(DockerImageName.parse("postgres:13.3"))
.withDatabaseName("test")
.withUsername("test")
.withPassword("test");
postgresContainer.start();
}
@AfterAll
public static void teardown() {
if (postgresContainer != null) {
postgresContainer.stop();
}
}
@Test
public void testSomething() {
// 使用Testcontainers创建的数据库实例进行测试操作
String jdbcUrl = postgresContainer.getJdbcUrl();
String username = postgresContainer.getUsername();
String password = postgresContainer.getPassword();
// 执行测试操作
}
}
在此示例中,我们使用了PostgreSQLContainer来创建一个PostgreSQL数据库实例,并在@BeforeAll方法中启动容器,在@AfterAll方法中停止容器。在@Test方法中,我们可以获取容器的JDBC URL、用户名和密码,并使用这些信息执行测试操作。
以上是在不使用Spring的情况下使用Testcontainers的一种解决方法,你可以根据具体的需求和数据库类型进行相应的调整。