According to https://docs.spring.io/spring-boot/docs/3.1.0-RC2/reference/htmlsingle/#features.testing.testcontainers
We could declare @Container as static field then use @ImportTestcontainers, but the following test fails, am I missed something?
package com.example.demo;
import static org.assertj.core.api.Assertions.assertThat;
import javax.sql.DataSource;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.testcontainers.context.ImportTestcontainers;
import org.testcontainers.containers.MySQLContainer;
import org.testcontainers.junit.jupiter.Container;
import com.zaxxer.hikari.HikariDataSource;
@SpringBootTest
public class ApplicationTests {
@Autowired
private DataSource dataSource;
@Test
void test() {
assertThat(dataSource).isInstanceOfSatisfying(HikariDataSource.class,
ds -> assertThat(ds.getJdbcUrl()).startsWith("jdbc:mysql://"));
}
@TestConfiguration
@ImportTestcontainers(Containers.class)
static class Config {
}
interface Containers {
@Container
MySQLContainer<?> mySQLContainer = new MySQLContainer<>("mysql:5.7");
}
}
plugins {
id 'java'
id 'org.springframework.boot' version '3.1.0-RC2'
id 'io.spring.dependency-management' version '1.1.0'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
repositories {
mavenCentral()
maven {
url "https://repo.spring.io/milestone"
}
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.boot:spring-boot-testcontainers'
testImplementation 'org.testcontainers:junit-jupiter'
testImplementation 'org.testcontainers:mysql'
testRuntimeOnly 'com.h2database:h2'
testRuntimeOnly 'com.mysql:mysql-connector-j'
}
tasks.named('test') {
useJUnitPlatform()
}
Comment From: quaff
Superseded by https://github.com/spring-projects/spring-boot/pull/35333