26 Aralık 2022 Pazartesi

Testcontainers GenericContainer Sınıfı

Giriş
Şu satırı dahil ederiz
import org.testcontainers.containers.GenericContainer;
constructor - dockerImageName
Örnek
Şöyle yaparız
GenericContainer redis = new GenericContainer("redis:5.0.8-alpine3.11")
  .withExposedPorts(6379);

redis.start();
// run your tests
redis.stop();
Örnek
Şöyle yaparız
@Rule
public GenericContainer<?> server = new GenericContainer(
  new ImageFromDockerFile()
    .withDockerfileFromBuilder(builder ->
      builder
        .from("alpine:3.16")
        .run("apk add --update nginx")
        .cmd("nginx", "-g", "deamon off;")
        .build()))
  .withExposedPorts(80);
getHost metodu
Açıklaması şöyle
When running with a local Docker daemon, exposed ports will usually be reachable on localhost. However, if you ever need to obtain the container address, you can do:
String ipAddress = container.getHost();
getMappedPort metodu
Açıklaması şöyle
We usually don’t want to publish to a specific port on the host, to avoid port collisions with locally running software or in between parallel test runs, so we let the Docker decide on which port to publish.

Since we don’t know the port Docker will pick, Testcontainers has additional APIs to get the actual mapped port after the container starts, so we can inject it into our tests and use it.

This can be done using the getMappedPort method, which takes the original (container) port as an argument, so for the Redis generic container example, you would do the following:

Integer mappedPort = container.getMappedPort(6379);
start metodu
Açıklaması şöyle
The start command is a blocking command, which means that it will wait until the application inside the container is ready. By default, it will wait for the container’s mapped network port to start listening. Of course, readiness can mean different things in different applications, that’s why there are other specific wait strategies that can be used with Testcontainers, but the default behavior should be already enough for most applications.
stop metodu
Açıklaması şöyle
The stop command will shut down and delete the container after the test.
Waiting for containers to start or be ready
Örnek - Http
Şöyle yaparız. Burada nginx sunucusu kullanıldığı için http isteğine cevap vermesi yeterli
GenericContainer nginxWithHttpWait = 
  new GenericContainer(DockerImageName.parse("nginx:1.9.4"))
  .withExposedPorts(80)
  .waitingFor(Wait.forHttp("/"));



Hiç yorum yok:

Yorum Gönder