2020年12月22日 | Leave a comment 问题: 单元测试中如何注入 FeignClient 解决: //------------- // HelloControllerTest @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) @AutoConfigureMockMvc @ActiveProfiles("unittest") @EnableFeignClients(basePackages = "demo.api") public abstract class UserControllerTest { @Test void testGet(@Autowired UserClient client) { var r = client.get("tcm_tenant"); assertNotNull(r); } } //--------- //application-unittest.yml server: port: 10020 feign: client: config: apiaa: url: http://localhost:${server.port} ------ //UserClient.java package demo.api; @FeignClient(name = "api1", contextId = "UserClient", url = "${feign.client.config.api1.url}") public interface UserClient { @GetMapping("/v1/user") UserResp get(@RequestParam("id") @NotBlank String id); } 123456789101112131415161718192021222324252627282930313233343536 //-------------// HelloControllerTest @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)@AutoConfigureMockMvc@ActiveProfiles("unittest")@EnableFeignClients(basePackages = "demo.api")public abstract class UserControllerTest { @Test void testGet(@Autowired UserClient client) { var r = client.get("tcm_tenant"); assertNotNull(r); }} //---------//application-unittest.yml server: port: 10020feign: client: config: apiaa: url: http://localhost:${server.port} ------//UserClient.java package demo.api;@FeignClient(name = "api1", contextId = "UserClient", url = "${feign.client.config.api1.url}")public interface UserClient { @GetMapping("/v1/user") UserResp get(@RequestParam("id") @NotBlank String id); } 参考: