This library provides Junit 4 Rule and Junit 5 Extension for starting an elasticsearch server on the local machine.
With JUnit 4 you can declare and use Elasticsearch rule as follows:
private static final String ELASTICSEARCH_CLUSTER_NAME = "elasticsearch";
@ClassRule
public static final ElasticsearchRule elasticsearchRule = new ElasticsearchRule(ELASTICSEARCH_CLUSTER_NAME);
private static TransportClient transportClient;
@BeforeClass
public static void setUpClass() {
transportClient = elasticsearchRule.getTransportClient();
}
@Test
public void testClient() {
String indexName = "twitter";
CreateIndexResponse createIndexResponse = transportClient.admin().indices().prepareCreate(indexName).get();
Assert.assertTrue(createIndexResponse.isAcknowledged());
}
It is also possible to get the network address of the Elasticsearch server and construct the TransportClient:
@BeforeClass
public static void setUpClass() {
String address = elasticsearchRule.getAddress();
String elasticsearchHost = address.split(":")[0];
int elasticsearchPort = Integer.parseInt(address.split(":")[1]);
InetAddress elasticsearchInetAddress;
try {
elasticsearchInetAddress = InetAddress.getByName(elasticsearchHost);
} catch (UnknownHostException e) {
throw new AssertionError("Cannot get the elasticsearch server address " + elasticsearchHost + ".", e);
}
Settings settings = Settings.builder().put("cluster.name", ELASTICSEARCH_CLUSTER_NAME).build();
transportClient = new PreBuiltTransportClient(settings);
transportClient.addTransportAddress(new TransportAddress(elasticsearchInetAddress, elasticsearchPort));
}
In case of using Junit 5, you can use ElasticsearchExtension like this:
private static final String ELASTICSEARCH_CLUSTER_NAME = "elasticsearch";
@RegisterExtension
static ElasticsearchExtension elasticsearchExtension = new ElasticsearchExtension(ELASTICSEARCH_CLUSTER_NAME);
private static TransportClient transportClient;
@BeforeAll
static void setUpClass(){
transportClient = elasticsearchExtension.getTransportClient();
}
@Test
public void testClient(){
String indexName = "twitter";
CreateIndexResponse createIndexResponse = transportClient.admin().indices().prepareCreate(indexName).get();
Assert.assertTrue(createIndexResponse.isAcknowledged());
}
You can refer to this library by either of java build systems (Maven, Gradle, SBT or Leiningen) using snippets from this jitpack link:
JUnit 4 and 5 dependencies are marked as optional, so you need to provide JUnit 4 or 5 dependency (based on what version you need, and you use) in you project to make it work.