gpt4 book ai didi

java - 模拟 FeignClient 响应

转载 作者:行者123 更新时间:2023-11-30 10:38:48 25 4
gpt4 key购买 nike

是否可以通过 MockRestServiceServer(restTemplate) 模拟响应 FeignClient?这个例子不起作用:

Application.class

@SpringBootApplication
@EnableFeignClients
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

}

TicketService.class

@FeignClient("ws")
public interface TicketService {

@RequestMapping(value = "/tickets/")
List<Ticket> findAllTickets();

}

TestConfig.class

@Profile("test")
@Configuration
public class TestConfig {

@Bean
@Primary
public RestTemplate restTemplate() {
return new RestTemplate();
}

}

MyTest.class

@ActiveProfiles("test")
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Application.class}, properties = {"ws.ribbon.listOfServers:example.com"})
public class MyTest {

@Autowired
RestTemplate restTemplate;
@Autowired
DispatcherService dispatcherService; // service where the execution of the method TicketService.findAllTickets();

private MockRestServiceServer mockServer;

@Before
public void setUp() {
mockServer = MockRestServiceServer.createServer(restTemplate);
}

@Test
public void ticket() {
mockServer.expect(requestTo("http://example.com/tickets/"))
.andExpect(method(HttpMethod.GET))
.andRespond(withSuccess(new ClassPathResource("tickets.json"), MediaType.APPLICATION_JSON));
dispatcherService.run();
}
}

但是向真实服务器 example.com 发出请求。

最佳答案

目前我知道 2 个好的方法:

  1. 使用 wiremock 库(对于 Spring Boot,我使用 spring-cloud-contract-wiremock)
  2. Mockito(我使用@MockBean)

关于java - 模拟 FeignClient 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39569642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com