【问题标题】:Define ElasticsearchIntegrationTest client in the test context xml在测试上下文 xml 中定义 ElasticsearchIntegrationTest 客户端
【发布时间】:2015-09-25 07:42:25
【问题描述】:

在我们的应用程序中,我们正在集成 ES。 有一个注入了 ElasticsearchTemplate 的存储库:

@Repository
public class ElasticSearchRepositoryImpl implements ElasticSearchRepository {
    private ElasticsearchTemplate elasticsearchTemplate;
    @Autowired
        public ElasticSearchRepositoryImpl(ElasticsearchTemplate elasticsearchTemplate){
            this.elasticsearchTemplate = elasticsearchTemplate;
        }

在测试方面,我们正在使用文档中定义的ElasticsearchIntegrationTest 类。 测试有自己的上下文,但由于存储库使用@Repository 注释进行注释,因此它正在加载,这使我在测试上下文中定义了一个ElasticsearchTemplate
在这一点上,我不想定义模板,因为如果是这样,我将需要定义一个客户端,并且由于我将在测试中使用ElasticsearchIntegrationTest 提供的client(),这没有任何意义。 我有不同的可能性:

  1. 在测试上下文中排除存储库 - 这正在被其他 bean 使用,我必须排除很多东西并处理很多问题,此外我认为这不是干净的。

  2. 声明没有客户端的模板(我也不喜欢这种可能性):

  3. 在测试上下文的模板定义中使用ElasticsearchIntegrationTest提供的客户端——我不知道怎么做,欢迎任何提示。

非常欢迎任何其他对我有帮助的解决方案、示例或想法。 提前致谢

对于我的解决方案 2,我在这里发布了我的代码,无法在上面发布:

<bean name="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
        <constructor-arg name="client"><null /></constructor-arg><!-- TODO: this client should be manually injected in the tests -->
    </bean>

【问题讨论】:

    标签: spring elasticsearch integration-testing spring-data-elasticsearch


    【解决方案1】:

    在 Spring 应用程序中,使用 Elasticsearch 创建集成测试的最简单方法是实例化一个嵌入式节点。

    @Configuration
    public class MyTestConfiguration {
        // create and start an ES node
        @Bean
        public Client client() {
            Settings settings = ImmutableSettings.builder()
                    .put("path.data", "target/data")
                    .build();
    
            Node node = NodeBuilder.nodeBuilder().local(true).settings(settings).node();
            return node.client();
        }
    
        // initialize your ES template
        @Bean
        public ElasticsearchTemplate elasticsearchTemplate(Client client) {
            return new ElasticsearchTemplate(client);
        }
    
    }
    

    如果您使用 Spring Boot 和 Spring Data Elasticsearch,它会在提供任何配置时自动创建一个嵌入式节点。

    【讨论】:

      猜你喜欢
      • 2011-05-07
      • 2010-12-28
      • 1970-01-01
      • 1970-01-01
      • 2013-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多