Java embedded Elasticsearch for integration testing

Default featured post

Java embedded Elasticsearch for integration testing. Embedded Elasticsearch was deprecated in version 5.0 and above. This causes many issues especially when it comes to integration testing.

One possible remedy is to run Elasticsearch in a Docker container but unfortunately, that has its own problems. For instance, you cannot run the Elasticsearch in Docker in Docker. Besides that. you need to do extra configurations if you want to run the Elasticsearch when your tests are running.

An easier approach is to use community versions of embedded Elasticsearch.

Fortunately, in the Java world, some projects do exist to provide embedded Elasticsearch, especially for testing. So far the best of all is embedded-elasticsearch by Allegro. The project supports 1.x, 2.x, 5.x and 6.x versions of Elasticsearch. The only caveat of this project is that you cannot run it under root user like any Elasticsearch cluster.

Setting it up is pretty easy. You just need to import the dependency to your project like this for Maven projects:

After that, you can bootstrap and shut down the embedded Elasticsearch in your Java integration test like this:

As you can see, we started the embedded Elasticsearch in setup method which is annotated with @Beforeall. This means that the embedded Elasticsearch will bootstrap before any tests start running.

Then after running all the test cases, we shut down the embedded Elasticsearch in teardown method which is annotated with @Afterall.

And that’s all. Happy testing!

More reading on Java JUnit5, here.