JUnit Rule for ElasticSearch

While I am using Solr a lot in my current engagement I recently started a pet project with ElasticSearch to learn more about it. Some of its functionality is rather different from Solr so there is quite some experimentation involved. I like to start small and implement tests if I like to find out how things work (see this post on how to write tests for Solr).

ElasticSearch internally uses TestNG and the test classes are not available in the distributed jar files. Fortunately it is really easy to start an ElasticSearch instance from within a test so it's no problem to do something similar in JUnit. Felix Müller posted some useful code snippets on how to do this, obviously targeted at a Maven build. The ElasticSearch instance is started in a setUp method and stopped in a tearDown method:

private EmbeddedElasticsearchServer embeddedElasticsearchServer;

public void startEmbeddedElasticsearchServer() {
embeddedElasticsearchServer = new EmbeddedElasticsearchServer();

public void shutdownEmbeddedElasticsearchServer() {

As it is rather cumbersome to add these methods to all tests I transformed the code to a JUnit rule. Rules can execute code before and after a test is run and influence its execution. There are some base classes available that make it really easy to get started with custom rules.

Our ElasticSearch example can be easily modeled using the base class ExternalResource (see the full example code on GitHub):

public class ElasticsearchTestNode extends ExternalResource {

private Node node;
private Path dataDirectory;

protected void before() throws Throwable {
try {
dataDirectory = Files.createTempDirectory("es-test", new FileAttribute []{});
} catch (IOException ex) {
throw new IllegalStateException(ex);

ImmutableSettings.Builder elasticsearchSettings = ImmutableSettings.settingsBuilder()
.put("http.enabled", "false")
.put("path.data", dataDirectory.toString());

node = NodeBuilder.nodeBuilder()

protected void after() {
try {
} catch (IOException ex) {
throw new IllegalStateException(ex);

public Client getClient() {
return node.client();

The before method is executed before the test is run so we can use it to start ElasticSearch. All data is written to a temporary folder. The after method is used to stop ElasticSearch and delete the folder.

In your test you can now just use the rule, either with the @Rule annotation to have it triggered on each test method, or using @ClassRule to execute it only once per class:

public class CoreTest {

public ElasticsearchTestNode testNode = new ElasticsearchTestNode();

public void indexAndGet() throws IOException {
testNode.getClient().prepareIndex("myindex", "document", "1")
.setSource(jsonBuilder().startObject().field("test", "123").endObject())

GetResponse response = testNode.getClient().prepareGet("myindex", "document", "1").execute().actionGet();

As it is really easy to implement custom rules I think this is a feature I will be using more often in the future.