您可以使用以下代码示例来解决此问题:
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.MySQLContainer;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class MyTest {
@Test
void shouldConnectToDatabase() {
try (MySQLContainer mysql = new MySQLContainer<>("mysql:latest")
.withUsername("root")
.withPassword("password")) {
mysql.start();
assertTrue(mysql.isRunning());
// Use container's IP and port to connect to the database
String jdbcUrl = String.format("jdbc:mysql://%s:%s/testdb", mysql.getContainerIpAddress(),
mysql.getMappedPort(MySQLContainer.MYSQL_PORT));
// Connect to the database using the jdbcUrl
}
}
}
在此示例中,我们创建了一个实例MySQLContainer
,并指定了正确的用户名和密码以连接到数据库。然后,我们启动MySQL容器,检查容器是否运行,并使用getContainerIpAddress()
和getMappedPort(MySQLContainer.MYSQL_PORT)
从容器中检索IP地址和端口。最后,我们使用连接字符串jdbc:mysql://<ip address>:<port>/testdb
连接到数据库。