模拟FeignClient响应

时间:2016-09-19 09:25:32

标签: java testing spring-boot spring-cloud-feign feign

可以通过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。

1 个答案:

答案 0 :(得分:1)

目前我知道两种不错的方法:

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