本文介绍了Elasticsearch Spring Boot集成测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找将嵌入式Elasticsearch添加到我的Spring Boot集成测试中的方法。



我看过弹性搜索集成测试,但它不能与Spring Boot一起使用,因为两者都应使用不同的测试运行器。



不幸的是,我有一个下面的类测试,它无法正常工作:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = App.class)
@WebAppConfiguration
@IntegrationTest("server.port:0")
public class TestExample extends ElasticsearchIntegrationTest {

    TestRestTemplate testRestTemplate = new TestRestTemplate();

    @Value("${local.server.port}")
    int port;

    @Test
    public void testOne(){
        ResponseEntity<String> results = testRestTemplate.getForEntity(String.format("http://localhost:%d/client/1", port), String.class);



     System.out.print(results);
    }

}

Does anybody has some ideas how to make them run or what is alternatives ??

解决方案

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

}

这篇关于Elasticsearch Spring Boot集成测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 21:04
查看更多