21 Eylül 2021 Salı

SpringTest Testcontainers GenericContainer Sınıfı

GenericContainer Sınıfı
Şu satırı dahil ederiz
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.Network;
import org.testcontainers.containers.wait.strategy.Wait;
Belirtilen docker image'ını çalıştırır

getHost metodu
Örnek
Şöyle yaparız
@Testcontainers
public class GenericContainerTest {

  private static final int INTERNAL_MARIO_PORT = 8080;

  @Container
  private GenericContainer marioContainer =
new GenericContainer(DockerImageName.parse("pengbai/docker-supermario"))
    .withExposedPorts(INTERNAL_MARIO_PORT);

  @Test
  public void testRunningMario() throws IOException {

    String host = marioContainer.getHost();
    int exposedPort = marioContainer.getMappedPort(INTERNAL_MARIO_PORT);

    URL url = new URL("http://" + host + ":" + exposedPort);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("GET");

    assertEquals(200, con.getResponseCode());
  }
}
withCopyFileToContainer metodu
Örnek
Şöyle yaparız
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.utility.MountableFile;

String dockerImageName = "hazelcast/hazelcast:latest";
GenericContainer<?> hazelcastContainer = new GenericContainer<>(dockerImageName)
  .withExposedPorts(5701)
  .withCopyFileToContainer(MountableFile.forClasspathResource("/hazelcast-server.xml"),
					"/opt/hazelcast/config/hazelcast.xml")
  .withEnv("HAZELCAST_CONFIG", "/opt/hazelcast/config/hazelcast.xml");

hazelcastContainer.start();
witEnv metodu
Örnek
Şöyle yaparız
GenericContainer<?> container = new GenericContainer<>("...")
  .withExposedPorts(8080)
  .withNetwork(Network.newNetwork())
.withNetworkAliases("application")
.withEnv("JAVA_OPTS", "-Djava.net.preferIPv4Stack=true -Djava.net.preferIPv4Addresses=true") .waitingFor(Wait.forHealthcheck()); container.start();
withExposedPorts metodu
Örnek
Şöyle yaparız
@org.testcontainers.spock.Testcontainers
class RedisBackedCacheIntTest extends Specification {

  GenericContainer redis = new GenericContainer<>("redis:5.0.3-alpine")
    .withExposedPorts(6379)
}
withLogConsumer metodu
Container bilgilerini de loglar
Örnek
Şöyle yaparız
@Container
private GenericContainer marioContainer = 
  new GenericContainer(DockerImageName.parse("pengbai/docker-supermario"))
    .withLogConsumer(new Slf4jLogConsumer(LOGGER))
    .withExposedPorts(INTERNAL_MARIO_PORT);

Hiç yorum yok:

Yorum Gönder