You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JUnit测试运行时如何禁用Eureka Client初始化?

禁用Spring Boot测试中的Eureka Client

问题场景

我编写了一个用于测试Rest API的JUnit 5测试类,代码如下:

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

    @MockBean
    private ListsService listsService;

    @Autowired
    private MockMvc mockMvc;

    @Test
    void restTest() throws Exception {

        .....
    }
}

项目依赖中包含Eureka Server依赖,每次运行该JUnit测试时,Eureka Client都会自动启动,进而出现连接拒绝的错误日志:

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

我不需要启动Eureka Client,请问该如何禁用它?


解决方案

方法1:在@SpringBootTest中直接指定配置属性

修改测试类的@SpringBootTest注解,通过properties参数直接关闭Eureka Client相关配置:

@SpringBootTest(properties = {
    "eureka.client.enabled=false",
    "spring.cloud.discovery.enabled=false"
})
@AutoConfigureMockMvc
@ExtendWith(MockitoExtension.class)
public class ControllerTest {
    // 原有测试代码保持不变
}

方法2:使用@TestPropertySource加载临时配置

在测试类上添加@TestPropertySource注解,单独指定要覆盖的配置项:

@SpringBootTest
@AutoConfigureMockMvc
@ExtendWith(MockitoExtension.class)
@TestPropertySource(properties = {
    "eureka.client.enabled=false",
    "spring.cloud.discovery.enabled=false"
})
public class ControllerTest {
    // 原有测试代码保持不变
}

方法3:创建测试专用配置文件

在src/test/resources目录下创建application-test.yml(或application-test.properties),添加禁用配置:

eureka:
  client:
    enabled: false
spring:
  cloud:
    discovery:
      enabled: false

然后在测试类的@SpringBootTest中指定使用test环境:

@SpringBootTest(profiles = "test")
@AutoConfigureMockMvc
@ExtendWith(MockitoExtension.class)
public class ControllerTest {
    // 原有测试代码保持不变
}

以上三种方法都能阻止Eureka Client在测试启动时初始化,避免出现连接Eureka Server的错误日志。

内容的提问来源于stack exchange,提问作者Peter Penzov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 02:10:07