3

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

应用程序类

@SpringBootApplication
@EnableFeignClients
public class Application {

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

}

票务服务类

@FeignClient("ws")
public interface TicketService {

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

}

测试配置类

@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 发出请求。

4

1 回答 1

3

目前我知道两种好方法:

  1. 使用 wiremock 库(对于 Spring Boot,我使用spring-cloud-contract-wiremock
  2. Mockito(我使用@MockBean
于 2018-01-30T21:04:38.900 回答