Search code examples
spring-bootjunitspring-test

Disable Eureka client initialization during JUnit test run


I have this Junit 5 test which is used to test Rest API calls:

@SpringBootTest
@AutoConfigureMockMvc
@ExtendWith(MockitoExtension.class)
public class ControllerTest {

    @MockBean
    private ListsService listsService;

    @Autowired
    private MockMvc mockMvc;

    @Test
    void restTest() throws Exception {

        .....
    }
}

Into the project dependencies I have Eureka server dependency. Every time when I run this Junit test Eureka client is also started. How I can disable it? I don't need to run it. Looks like @SpringBootTest is also including Eureka client when test is run?

Error:

2023-06-28T18:28:59.213+03:00  WARN 9104 --- [nfoReplicator-0] c.n.d.s.t.d.RetryableEurekaHttpClient    : Request execution failed with message: I/O error on POST request for "http://localhost:8761/eureka/apps/MICROSERVICE": Connect to http://localhost:8761 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: no further information
2023-06-28T18:28:59.213+03:00  WARN 9104 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient    : DiscoveryClient_MICROSERVICE/localhost:MICROSERVICE:8798 - registration failed Cannot execute request on any known server

Solution

  • Add the property below to test's application.properties:

    eureka.client.enabled=false
    

    or add the property directly to @SpringBootTest annotation:

    @SpringBootTest(properties = "eureka.client.enabled=false")
    

    If you use that class to test the web layer, consider replacing @SpringBootTest with @WebMvcTest, to prevent loading the whole application context, which will make your test run faster.

    Using the @WebMvcTest annotation will disable full auto-configuration and instead apply only configuration relevant to MVC tests (i.e. @Controller, @ControllerAdvice, @JsonComponent, Converter/GenericConverter, Filter, WebMvcConfigurer and HandlerMethodArgumentResolver beans but not @Component, @Service or @Repository beans).

    For more details refer to Testing MVC Web Controllers with Spring Boot and @WebMvcTest.