add test-containers module

This commit is contained in:
Bahtiyar Kaba
2018-05-17 22:56:58 +03:00
committed by José Carlos Valero Sánchez
parent eac1e3c46c
commit c4d62a47da
4 changed files with 192 additions and 0 deletions
@@ -0,0 +1,45 @@
package com.baeldung.testconainers;
import static org.junit.Assert.assertEquals;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.platform.commons.annotation.Testable;
import org.testcontainers.containers.GenericContainer;
@Testable
public class GenericContainerTests {
@ClassRule
public static GenericContainer simpleWebServer = new GenericContainer("alpine:3.2")
.withExposedPorts(80)
.withCommand("/bin/sh", "-c", "while true; do echo "
+ "\"HTTP/1.1 200 OK\n\nHello World!\" | nc -l -p 80; done");
@Test
public void givenSimpleWebServerContainer_whenGetReuqest_thenReturnsResponse() throws Exception {
String address = "http://" + simpleWebServer.getContainerIpAddress() + ":" + simpleWebServer.getMappedPort(80);
String response = simpleGetRequest(address);
assertEquals(response, "Hello World!");
}
private String simpleGetRequest(String address) throws Exception {
URL url = new URL(address);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
return content.toString();
}
}
@@ -0,0 +1,36 @@
package com.baeldung.testconainers;
import static org.junit.Assert.assertEquals;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.platform.commons.annotation.Testable;
import org.testcontainers.containers.PostgreSQLContainer;
@Testable
public class PostgreSqlContainerTests {
@Rule
public PostgreSQLContainer postgresContainer = new PostgreSQLContainer();
@Test
public void whenSelectQueryExecuted_thenResulstsReturned() throws Exception {
ResultSet resultSet = performQuery(postgresContainer, "SELECT 1");
resultSet.next();
int result = resultSet.getInt(1);
assertEquals(1, result);
}
private ResultSet performQuery(PostgreSQLContainer postgres, String query) throws SQLException {
String jdbcUrl = postgres.getJdbcUrl();
String username = postgres.getUsername();
String password = postgres.getPassword();
Connection conn = DriverManager.getConnection(jdbcUrl, username, password);
return conn.createStatement()
.executeQuery(query);
}
}