Best Testcontainers-java code snippet using org.testcontainers.containers.SolrContainer
Source:AlfrescoContainer.java
...19 public static final int ALFRESCO_PORT = 8080;20 public static final int ALFRESCO_SSL_PORT = 8443;21 public static final int ALFRESCO_DEBUG_PORT = 8000;22 private Network network = Network.newNetwork();23 private SolrContainer solrContainer;24 private JdbcDatabaseContainer<?> databaseContainer;25 private String alfrescoVersion;26 public AlfrescoContainer(@NonNull Edition edition, @NonNull String version) {27 this((Edition.COMMUNITY.equals(edition) ? IMAGE_COMMUNITY : IMAGE_ENTERPRISE) + ":" + version);28 }29 public AlfrescoContainer(@NonNull String dockerImageName) {30 this(dockerImageName, ImageUtils.extractVersion(dockerImageName));31 }32 public AlfrescoContainer(@NonNull String dockerImage, @NonNull String alfrescoVersion) {33 super(dockerImage);34 withNetwork(network);35 this.alfrescoVersion = alfrescoVersion;36 // Alfresco cannot run without a DB: we provide PostgresSQL as a default37 withDatabase(defaultDatabase());38 }39 /**40 * In principle this can work with any database, as long as the DB driver is available in the image. TODO maybe it41 * is possible to include the DB driver automatically based on the DB used?42 */43 public SELF withDatabase(JdbcDatabaseContainer<?> database) {44 dependsOn(database);45 database.withNetwork(network);46 this.databaseContainer = database;47 return self();48 }49 public SELF withSolr(SolrContainer solr) {50 solr.dependsOn(this);51 solr.withNetwork(network);52 addExposedPort(ALFRESCO_SSL_PORT);53 this.solrContainer = solr;54 return self();55 }56 public SELF withDebug() {57 final String address =58 ((alfrescoVersion.startsWith("6") && !alfrescoVersion.startsWith("6.0")) ? "*:" : "")59 + ALFRESCO_DEBUG_PORT;60 withEnv("CATALINA_OPTS",61 "-agentlib:jdwp=transport=dt_socket,address=" + address + ",server=y,suspend=n");62 addExposedPort(ALFRESCO_DEBUG_PORT);63 return self();64 }65 @Override66 protected void configure() {67 this.setJavaOptsEnv();68 addExposedPort(ALFRESCO_PORT);69 waitingFor(Wait.forHttp("/alfresco").withStartupTimeout(Duration.ofSeconds(300)));70 }71 private void setJavaOptsEnv() {72 Map<String, String> javaOpts = new HashMap<>();73 javaOpts.put("messaging.subsystem.autoStart", Boolean.toString(false));74 includeDBOpts(javaOpts);75 includeSolrOpts(javaOpts);76 StringBuilder javaOptsValueBuilder = new StringBuilder();77 javaOpts.forEach((key, value) -> {78 javaOptsValueBuilder.append("-D")79 .append(key)80 .append("=")81 .append(value)82 .append(" ");83 });84 withEnv("JAVA_OPTS", javaOptsValueBuilder.toString());85 }86 private void includeDBOpts(final Map<String, String> javaOpts) {87 javaOpts.put("db.name", databaseContainer.getDatabaseName());88 javaOpts.put("db.driver", databaseContainer.getDriverClassName());89 javaOpts.put("db.host", databaseContainer.getNetworkAliases().get(0));90 javaOpts.put("db.port",91 Integer.toString(JdbcDatabaseContainerUtils.getInternalDatabasePort(databaseContainer)));92 javaOpts.put("db.username", databaseContainer.getUsername());93 javaOpts.put("db.password", databaseContainer.getPassword());94 javaOpts.put("db.url", JdbcDatabaseContainerUtils.getInternalJdbcUrl(databaseContainer));95 }96 private void includeSolrOpts(final Map<String, String> javaOpts) {97 if (solrContainer == null) {98 javaOpts.put("index.subsystem.name", "noindex");99 } else {100 javaOpts.put("index.subsystem.name", solrContainer.getVersion().getName());101 javaOpts.put("solr.host", solrContainer.getNetworkAliases().get(0));102 javaOpts.put("solr.port", Integer.toString(SolrContainer.SOLR_PORT));103 javaOpts.put("solr.port.ssl", Integer.toString(SolrContainer.SOLR_SSL_PORT));104 javaOpts.put("solr.secureComms", "https");105 }106 }107 public SolrContainer getSolrContainer() {108 return solrContainer;109 }110 public JdbcDatabaseContainer getDatabaseContainer() {111 return databaseContainer;112 }113 private static JdbcDatabaseContainer<?> defaultDatabase() {114 return new PostgreSQLContainer<>("docker.io/xenit/postgres:latest")115 .withDatabaseName("alfresco")116 .withUsername("alfresco")117 .withPassword("admin");118 }119}...
Source:BookLoaderIntegrationTest.java
1package de.qaware.demo.testcontainers;2import lombok.extern.slf4j.Slf4j;3import org.apache.solr.client.solrj.SolrClient;4import org.apache.solr.client.solrj.SolrQuery;5import org.apache.solr.client.solrj.impl.HttpSolrClient;6import org.junit.BeforeClass;7import org.junit.Test;8import org.testcontainers.containers.GenericContainer;9import org.testcontainers.containers.Network;10import org.testcontainers.containers.PostgreSQLContainer;11import org.testcontainers.containers.output.Slf4jLogConsumer;12import org.testcontainers.containers.wait.strategy.Wait;13import javax.ws.rs.client.Client;14import javax.ws.rs.client.ClientBuilder;15import javax.ws.rs.core.Response;16import static org.hamcrest.MatcherAssert.assertThat;17import static org.hamcrest.core.Is.is;18/**19 * An integration test for {@link BookLoader} with Docker containers using the Testcontainers library.20 */21@Slf4j22public class BookLoaderIntegrationTest {23 private static final String DOCKER_IMAGE_POSTGRES = "postgres:11.2";24 private static final String DOCKER_IMAGE_SOLR = "solr:7.7.1";25 private static final String DOCKER_IMAGE_LOADER = "testcontainers/book-loader:latest";26 private static final int PORT_SOLR = 8983;27 private static final int PORT_PAYARA_MICRO = 8080;28 private static final int PORT_DEBUGGER = 5005;29 private static GenericContainer solrContainer;30 private static GenericContainer loaderContainer;31 private static Client httpClient = ClientBuilder.newClient();32 @BeforeClass33 public static void setUp() {34 Network network = Network.newNetwork();35 // Postgres database36 new PostgreSQLContainer(DOCKER_IMAGE_POSTGRES)37 .withInitScript("insert-test-data.sql") // create schema and add test data38 .withDatabaseName("postgres")39 .withUsername("postgres")40 .withPassword("123")41 .withNetwork(network)42 .withNetworkAliases("testcontainers-demo-postgres")43 .start();44 // Solr search index45 solrContainer = new GenericContainer(DOCKER_IMAGE_SOLR)46 .withCommand("solr-create -c books") // create empty "books" core47 .withExposedPorts(PORT_SOLR)48 .withNetwork(network)49 .withNetworkAliases("testcontainers-demo-solr")50 .waitingFor(Wait.forHttp("/solr/books/select?q=*:*"));51 solrContainer.start();52 // Book-Loader micro service53 loaderContainer = new GenericContainer(DOCKER_IMAGE_LOADER)54 .withExposedPorts(PORT_PAYARA_MICRO, PORT_DEBUGGER)55 .withNetwork(network)56 .withNetworkAliases("testcontainers-demo-book-loader")57 .withLogConsumer(new Slf4jLogConsumer(log))58 .waitingFor(Wait.forLogMessage(".*Payara Micro .* ready.*\\n", 1));59 loaderContainer.start();60 }61 @Test62 public void testLoader() throws Exception {63 String baseSolrUrl = "http://" + solrContainer.getContainerIpAddress()64 + ":" + solrContainer.getMappedPort(PORT_SOLR) + "/solr/books";65 try (SolrClient solrClient = new HttpSolrClient.Builder(baseSolrUrl).build()) {66 // Given an empty Solr search index67 assertThat(solrClient.query(new SolrQuery("*:*")).getResults().size(), is(0));68 // When the Loader is executed69 String loaderUrl = "http://" + loaderContainer.getContainerIpAddress() + ":"70 + loaderContainer.getMappedPort(PORT_PAYARA_MICRO) + "/book-loader/start";71 Response loaderResponse = httpClient.target(loaderUrl).request().get();72 int status = loaderResponse.getStatus();73 String message = loaderResponse.readEntity(String.class);74 log.info("Loader response has status '{}' and message '{}'", status, message);75 // Then we should receive a successful response and Solr should be filled with data76 assertThat(status, is(Response.Status.OK.getStatusCode()));77 assertThat(message, is("Loaded 3 books"));78 assertThat(solrClient.query(new SolrQuery("*:*")).getResults().size(), is(3));79 }80 }81}...
Source:WarehouseServiceImplIntegrationTest.java
...3import com.bmuschko.testcontainers.repository.warehouse.db.UsernamePasswordCredentials;4import org.junit.jupiter.api.BeforeEach;5import org.junit.jupiter.api.Test;6import org.testcontainers.containers.PostgreSQLContainer;7import org.testcontainers.containers.SolrContainer;8import org.testcontainers.junit.jupiter.Container;9import org.testcontainers.junit.jupiter.Testcontainers;10import org.testcontainers.utility.DockerImageName;11import java.io.IOException;12import java.math.BigDecimal;13import java.net.URI;14import java.net.http.HttpClient;15import java.net.http.HttpRequest;16import java.net.http.HttpResponse;17@Testcontainers18public class WarehouseServiceImplIntegrationTest {19 private WarehouseService warehouseService;20 @Container21 private final PostgreSQLContainer postgreSQLContainer = (PostgreSQLContainer) new PostgreSQLContainer("postgres:9.6.12")22 .withInitScript("warehouse.sql")23 .withDatabaseName("warehouse");24 @Container25 private final SolrContainer solrContainer = new SolrContainer(DockerImageName.parse("solr:8.9.0"));26 @BeforeEach27 public void setUp() {28 UsernamePasswordCredentials postgreSqlCredentials = new UsernamePasswordCredentials(postgreSQLContainer.getUsername(), postgreSQLContainer.getPassword());29 String solrUrl = createSolrUrl();30 createProductsCollection(solrUrl);31 warehouseService = new WarehouseServiceImpl(postgreSQLContainer.getJdbcUrl(), postgreSqlCredentials, solrUrl);32 }33 @Test34 public void testInsertProduct() {35 Product product = new Product();36 product.setName("Clock");37 product.setPrice(new BigDecimal(39.99));38 product.setCategory("Household");39 warehouseService.addProduct(product);...
SolrContainer
Using AI Code Generation
1import java.io.IOException;2import java.util.ArrayList;3import java.util.List;4import org.apache.solr.client.solrj.SolrClient;5import org.apache.solr.client.solrj.SolrServerException;6import org.apache.solr.client.solrj.impl.HttpSolrClient;7import org.apache.solr.client.solrj.impl.HttpSolrClient.Builder;8import org.apache.solr.client.solrj.request.CollectionAdminRequest;9import org.apache.solr.client.solrj.response.CollectionAdminResponse;10import org.apache.solr.client.solrj.response.QueryResponse;11import org.apache.solr.common.SolrDocumentList;12import org.apache.solr.common.SolrInputDocument;13import org.junit.Before;14import org.junit.Test;15import org.testcontainers.containers.SolrContainer;16public class SolrContainerTest {17 private SolrContainer solrContainer;18 private SolrClient solrClient;19 public void setUp() {20 solrContainer = new SolrContainer();21 solrContainer.start();22 solrClient = new HttpSolrClient.Builder(solrContainer.getSolrUrl()).build();23 }24 public void testSolrContainer() throws SolrServerException, IOException {25 String collectionName = "testCollection";26 CollectionAdminRequest.Create createCollectionRequest = CollectionAdminRequest.createCollection(collectionName, 1, 1);27 CollectionAdminResponse createCollectionResponse = createCollectionRequest.process(solrClient);28 System.out.println("Create collection response: " + createCollectionResponse);29 List<SolrInputDocument> solrInputDocuments = new ArrayList<>();30 SolrInputDocument solrInputDocument = new SolrInputDocument();31 solrInputDocument.addField("id", "1");32 solrInputDocument.addField("name", "test");33 solrInputDocuments.add(solrInputDocument);34 solrClient.add(collectionName, solrInputDocuments);35 solrClient.commit(collectionName);36 QueryResponse queryResponse = solrClient.query(collectionName, new org.apache.solr.client.solrj.SolrQuery("*:*"));37 SolrDocumentList solrDocumentList = queryResponse.getResults();38 System.out.println("Response documents: " + solrDocumentList);39 }40}41Create collection response: {responseHeader={status=0, QTime=129}}42Response documents: {numFound=1, start=
SolrContainer
Using AI Code Generation
1import org.testcontainers.containers.SolrContainer;2public class SolrContainerTest {3 public static void main(String[] args) {4 SolrContainer solrContainer = new SolrContainer();5 solrContainer.start();6 System.out.println("SolrContainer is started");7 System.out.println("SolrContainer.getSolrUrl() = " + solrContainer.getSolrUrl());8 solrContainer.stop();9 }10}111. SolrContainer(String dockerImageName)122. SolrContainer(DockerImageName dockerImageName)133. SolrContainer()141. String getSolrUrl()152. String getSolrVersion()163. String getZookeeperConnectionString()174. String getZookeeperHost()185. Integer getZookeeperPort()196. String getSolrHome()207. String getSolrDataDir()
SolrContainer
Using AI Code Generation
1import org.testcontainers.containers.SolrContainer;2public class SolrTest {3 public static void main(String[] args) {4 SolrContainer solr = new SolrContainer();5 solr.start();6 System.out.println("Solr Container started");7 System.out.println("Solr Admin UI: " + solr.getSolrUrl());8 System.out.println("Solr Admin UI: " + solr.getSolrUrl() + "/admin");9 solr.stop();10 }11}12import org.testcontainers.containers.SolrContainer;13public class SolrTest {14 public static void main(String[] args) {15 SolrContainer solr = new SolrContainer("solr:8.6.3");16 solr.withConfigurationFromPath("solr-conf");17 solr.start();18 System.out.println("Solr Container started");19 System.out.println("Solr Admin UI: " + solr.getSolrUrl());20 System.out.println("Solr Admin UI: " + solr.getSolrUrl() + "/admin");21 solr.stop();22 }23}24In this example, we will create a Solr Container with custom configuration and custom port. We will use the SolrContainer class of org.testcontainers.containers package. We will create a new container using the constructor that accepts a Solr configuration file. We will use the getSolrUrl() method of SolrContainer class to get the URL of the Solr Admin UI. We will
SolrContainer
Using AI Code Generation
1package com.mycompany.app;2import org.testcontainers.containers.SolrContainer;3public class App {4 public static void main(String[] args) {5 SolrContainer solr = new SolrContainer();6 solr.start();7 System.out.println("Solr is running at " + solr.getSolrUrl());8 solr.stop();9 }10}11package com.mycompany.app;12import org.testcontainers.solr.SolrContainer;13public class App {14 public static void main(String[] args) {15 SolrContainer solr = new SolrContainer();16 solr.start();17 System.out.println("Solr is running at " + solr.getSolrUrl());18 solr.stop();19 }20}21 at org.testcontainers.utility.DockerImageName.parse(DockerImageName.java:112)22 at org.testcontainers.containers.GenericContainer.getDockerImageName(GenericContainer.java:1289)23 at org.testcontainers.containers.GenericContainer.logger(GenericContainer.java:570)24 at org.testcontainers.containers.GenericContainer.doStart(GenericContainer.java:317)25 at org.testcontainers.containers.GenericContainer.start(GenericContainer.java:301)26 at org.testcontainers.containers.SolrContainer.start(SolrContainer.java:92)27 at com.mycompany.app.App.main(App.java:8)28Your name to display (optional):29Your name to display (optional):
SolrContainer
Using AI Code Generation
1import org.testcontainers.containers.SolrContainer;2import org.testcontainers.containers.GenericContainer;3public class SolrContainerTest {4 public static void main(String[] args) {5 try (SolrContainer solrContainer = new SolrContainer()) {6 solrContainer.start();7 System.out.println("Solr Container started");8 System.out.println("Solr Container image name is " + solrContainer.getDockerImageName());9 System.out.println("Solr Container port is " + solrContainer.getFirstMappedPort());10 System.out.println("Solr Container host is " + solrContainer.getContainerIpAddress());11 System.out.println("Solr Container url is " + solrContainer.getSolrUrl());12 System.out.println("Solr Container logs are " + solrContainer.getLogs());13 }14 }15}
SolrContainer
Using AI Code Generation
1package org.testcontainers.containers;2import org.junit.jupiter.api.Test;3import org.testcontainers.junit.jupiter.Container;4import org.testcontainers.junit.jupiter.Testcontainers;5public class SolrContainerTest {6 public static SolrContainer solrContainer = new SolrContainer();7 public void testSolrContainer() {8 solrContainer.start();9 System.out.println("Solr Container
SolrContainer
Using AI Code Generation
1import org.testcontainers.containers.SolrContainer;2import java.io.IOException;3{4 public static void main(String[] args) throws IOException, InterruptedException {5 SolrContainer solrContainer = new SolrContainer("solr:8.8.1");6 solrContainer.start();7 System.out.println("Solr Container is started");8 }9}
SolrContainer
Using AI Code Generation
1package org.testcontainers.containers;2import org.testcontainers.containers.wait.strategy.Wait;3import org.testcontainers.utility.DockerImageName;4public class SolrContainer extends GenericContainer<SolrContainer> {5 private static final DockerImageName DEFAULT_IMAGE_NAME = DockerImageName.parse("solr");6 private static final String DEFAULT_TAG = "8.5.0";7 public SolrContainer() {8 this(DEFAULT_IMAGE_NAME.withTag(DEFAULT_TAG));9 }10 public SolrContainer(final String dockerImageName) {11 this(DockerImageName.parse(dockerImageName));12 }13 public SolrContainer(final DockerImageName dockerImageName) {14 super(dockerImageName);15 this.waitStrategy = Wait.forLogMessage(".*o.e.j.s.Server.*started.*\\n", 1);16 }17 protected Integer getLivenessCheckPort() {18 return getMappedPort(8983);19 }20}21package org.testcontainers.containers;22import org.testcontainers.containers.wait.strategy.Wait;23import org.testcontainers.utility.DockerImageName;24public class SolrContainer extends GenericContainer<SolrContainer> {25 private static final DockerImageName DEFAULT_IMAGE_NAME = DockerImageName.parse("solr");26 private static final String DEFAULT_TAG = "8.5.0";27 public SolrContainer() {28 this(DEFAULT_IMAGE_NAME.withTag(DEFAULT_TAG));29 }30 public SolrContainer(final String dockerImageName) {31 this(DockerImageName.parse(dockerImageName));32 }33 public SolrContainer(final DockerImageName dockerImageName) {34 super(dockerImageName);35 this.waitStrategy = Wait.forLogMessage(".*o.e.j.s.Server.*started.*\\n", 1);36 }37 protected Integer getLivenessCheckPort() {38 return getMappedPort(8983);39 }40}41package org.testcontainers.containers;42import org.testcontainers.containers.wait.strategy.Wait;43import org.testcontainers.utility.DockerImageName;
SolrContainer
Using AI Code Generation
1import org.testcontainers.containers.SolrContainer;2public class 1 {3public static void main(String[] args) {4SolrContainer container = new SolrContainer();5container.start();6System.out.println("Container name is: " + container.getContainerName());7System.out.println("Container port is: " + container.getFirstMappedPort());8System.out.println("Container IP address is: " + container.getContainerIpAddress());9container.stop();10}11}
SolrContainer
Using AI Code Generation
1import org.testcontainers.containers.SolrContainer;2import org.apache.solr.client.solrj.impl.HttpSolrClient;3import org.apache.solr.client.solrj.SolrQuery;4import org.apache.solr.client.solrj.SolrClient;5import org.apache.solr.client.solrj.response.QueryResponse;6import org.apache.solr.common.SolrDocumentList;7import org.apache.solr.client.solrj.response.UpdateResponse;8import org.apache.solr.common.SolrInputDocument;9public class SolrContainerExample {10 public static void main(String[] args) throws Exception {11 try (SolrContainer solr = new SolrContainer()) {12 solr.start();13 SolrClient client = new HttpSolrClient.Builder(solr.getSolrUrl()).build();14 SolrInputDocument doc = new SolrInputDocument();15 doc.addField("id", "1");16 doc.addField("name", "Test");17 UpdateResponse response = client.add("collection1", doc);18 client.commit("collection1");19 SolrQuery query = new SolrQuery();20 query.setQuery("*:*");21 QueryResponse resp = client.query("collection1", query);22 SolrDocumentList docs = resp.getResults();23 System.out.println("Found " + docs.getNumFound() + " documents");24 System.out.println("Document 1: " + docs.get(0));25 }26 }27}28Document 1: {name=Test, id=1}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!