Elasticsearch Spring boot integration test Elasticsearch Spring boot integration test elasticsearch elasticsearch

Elasticsearch Spring boot integration test


You can actually do what you need without any additional elasticsearch testing dependencies. The idea is basically to create an embedded node and then use the NodeClient to communicate with it.

For that, I created my own EmbeddedElasticsearchServer class which looks (more or less) like this:

public class EmbeddedElasticsearchServer implements InitializingBean {    public EmbeddedElasticsearchServer() {        ImmutableSettings.Builder elasticsearchSettings = ImmutableSettings.settingsBuilder()                .put("http.enabled", "false")                .put("path.data", "target/elasticsearch-data");        node = nodeBuilder()                .local(true)                .settings(elasticsearchSettings.build())                .node();        client = node.client();    }    @Override    public void afterPropertiesSet() throws Exception {         // Initialization stuff:         // - create required indices         // - define mappings         // - populate with test data    }    public Client getClient() {         return client;    }}

Then, in spring configuration (let's call it integration-test-context.xml) I did this:

<bean id="embeddedElasticsearchServer"       class="com.example.EmbeddedElasticsearchServer" /><bean id="elasticsearchClient"      class="org.elasticsearch.client.node.NodeClient"       factory-bean="embeddedElasticsearchServer"       factory-method="getClient" />

Then you can just autowire the client in your test like this:

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("/integration-test-context.xml")public abstract class AbstractElasticsearchIntegrationTest {    @Autowired    private Client elasticsearchClient;    // Your rests go here...}