Search code examples
spring-bootelasticsearchjunit5spring-boot-test

Exclude elasticsearchTemplate from Spring-Boot Test


I have an application that use Elasticsearch and I'd like to disable this integration when I'm testing some controllers. How can I disable elasticsearchTemplate on Spring-Boot test?

Application.class:

@SpringBootApplication
@EnableElasticsearchRepositories(basePackages = "com.closeupinternational.comclosure.elasticsearch")
public class Application {
...

Repository.class:

@Repository
public interface PipelineRepository extends ElasticsearchRepository<Pipeline, String> {
...

Test Controller.class:

@ExtendWith(SpringExtension.class)
@EnableAutoConfiguration(exclude = {ElasticsearchDataAutoConfiguration.class,
ElasticsearchRepositoriesAutoConfiguration.class})
@WebMvcTest(ProductionCycleExecutionController.class)
@Slf4j
public class ProductionCycleExecutionControllerTest {

    @Autowired
    private MockMvc mvc;

    @MockBean
    private ProductionCycleExecutionService prodCycleExecService;

    ...

I'm not using inside ProductionCycleExecutionService and I don't wanna try to test elasticsearch repository PipelineRepository at this moment.

Error:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'pipelineRepository' defined in 
com.closeupinternational.comclosure.elasticsearch.PipelineRepository defined in
 @EnableElasticsearchRepositories declared on Application: Cannot resolve reference to bean 
'elasticsearchTemplate' while setting bean property 'elasticsearchOperations'; nested exception is org.springframework.beans.factory

Solution

  • Just remove @ExtendWith(SpringExtension.class) and @EnableAutoConfiguration(exclude = {ElasticsearchDataAutoConfiguration.class, ElasticsearchRepositoriesAutoConfiguration.class})

    These annotations aim to bootstrap the whole Spring context and configure it

    @WebMvcTest should be enough in your case as it bootstraps web-related context only

    Upd

    If you have any dependencies in your ProductionCycleExecutionController (like elasticsearchTemplate you mentioned) then mock them like this if you don't need to define their behavior, as follows:

    @MockBeans(value = {@MockBean(YourBean1.class), @MockBean(YourBean2.class), @MockBean(YourBean3.class)})
    

    If you do need to define mocking behavior then mock as property in class:

    @MockBean
    private YourBean yourBean;