Blanca Hdez
Blanca Hdez

Reputation: 3563

Define ElasticsearchIntegrationTest client in the test context xml

In our application we are integrating ES. There is a repository with an ElasticsearchTemplate injected:

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

In the tests side, we are making use of the ElasticsearchIntegrationTest class as defined in the documentation. The tests have their own context, but since the repository is being annotated with the @Repository annotation, it is being loaded and this makes me define an ElasticsearchTemplate in the test context.
At this point, I dont want to define a template, because if so I would need to define a client and since I am going to use in the tests the client() provided by the ElasticsearchIntegrationTest, this would make no sense.
I have different possibilities:

  1. Exclude in the test context the repository - this is being used by other beans and I would have to exclude many things and deal with a lot of problems, besides I don't think is clean.

  2. Declare the template with no client (I don't like this possibility either):

  3. Use the client provided by the ElasticsearchIntegrationTest in the template definition within the test context - I don't know how to do this, any hint would be welcome.

Any other solution, example or idea that helps me would be very welcome. Thanks in advance

For my solution 2 I post here my code, could not post it above:

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

Upvotes: 2

Views: 547

Answers (1)

Quentin
Quentin

Reputation: 511

From a Spring Application, the easiest way to create an integration test with Elasticsearch is to instanciate an embedded node.

@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);
    }

}

If you use Spring Boot and Spring Data Elasticsearch, it will create an embedded node automatically when any configuration is provided.

Upvotes: 1

Related Questions