Spring Boot WireMock junit5不模拟外部调用

问题描述

我的FristService内部通过SecondService调用feign client,而我正在尝试为FirstService编写测试,并希望模拟对第二个服务的调用

wiremock似乎无法拦截并响应模拟结果,但抛出以下异常(因为它不是在模拟)

java.lang.RuntimeException: com.netflix.client.ClientException: Load balancer does not have available server for client: second-service
    at org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient.execute(LoadBalancerFeignClient.java:90)
    at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:119)

这是测试代码

@SpringBoottest(webEnvironment = SpringBoottest.WebEnvironment.RANDOM_PORT)
@ContextConfiguration(initializers = {wiremockInitializer.class})
@AutoConfiguremockmvc
public class TestFirstController {

    @Autowired
    private wiremockServer wiremockServer;

    @Inject
    public mockmvc mockmvc;

    @LocalServerPort
    private Integer port;

    @AfterEach
    public void afterEach() {
        this.wiremockServer.resetAll();
    }

    @Test
    public void testSomeMethod() throws Exception {
        this.wiremockServer.stubFor(
                wiremock.get(urlPathMatching("/second-controller/1"))
                        .willReturn(aResponse()
                                .withHeader("Content-Type",MediaType.APPLICATION_JSON_VALUE)
                                .withBody("[{\"id\":1,\"message\":\"Child title 1\"}]"))
        );

        mockmvc.perform(mockmvcRequestBuilders.request(HttpMethod.GET,"/first-controller/1"))
                .andDo(mockmvcResultHandlers.print())
                .andExpect(status().isOk());

    }
}

这是我的业务方法,该方法首先从数据库获取记录,然后调用第二个服务

@Override
public First getFirst(Integer id) {
    First first = map(respository.findById(id));
    
    //feign-client call
    List<Second> seconds = client.getSeconds(id);
    first.setChild(seconds);

    return first;
}

这是我的假冒客户,在测试模式下,我没有做任何更改

@FeignClient("service-2")
public interface SecondApi {
    @GetMapping({"/second-controller/{id}"})
    SomeData getData(@PathVariable("id") Integer id);
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)