@TestConfiguration
public class ESRestClientTestConfig {
private static final String ELASTICSEARCH_VERSION = "8.7.0";
private static final DockerImageName ELASTICSEARCH_IMAGE = DockerImageName
.parse("docker.elastic.co/elasticsearch/elasticsearch")
.withTag(ELASTICSEARCH_VERSION);
/**
* Elasticsearch default username, when secured
*/
private static final String ELASTICSEARCH_USERNAME = "elastic";
/**
* Optionally activate security with a default password.
*/
private static final String ELASTICSEARCH_PASSWORD = "changeme";
@Container
private static final ElasticsearchContainer container = new ElasticsearchContainer(ELASTICSEARCH_IMAGE)
.withPassword(ELASTICSEARCH_PASSWORD);
@Bean
public ElasticsearchContainer elasticsearchContainer() {
return container;
}
@Bean
public ElasticsearchClient elasticsearchClient() {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials(ELASTICSEARCH_USERNAME, ELASTICSEARCH_PASSWORD));
String protocol = container.caCertAsBytes().isPresent() ? "https://" : "http://";
RestClient restClient = RestClient
.builder(HttpHost.create(protocol + container.getHttpHostAddress()))
.setHttpClientConfigCallback(httpClientBuilder -> {
if (container.caCertAsBytes().isPresent()) {
httpClientBuilder.setSSLContext(container.createSslContextFromCa());
}
return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
})
.build();
// Create the transport with a Jackson mapper
ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
// And create the API client
return new ElasticsearchClient(transport);
}
}
Will this test configuration works for elasticsearch test containers
I need to write unit tests for a specific class that interacts with Elasticsearch. There will be only data retrieving and I need this test configuration file to be reused.