Elasticsearch Spring boot integration test

笑着哭i 提交于 2019-12-04 23:44:47

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...

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!