2016-09-19 83 views
2

可以通過MockRestServiceServer(restTemplate)模擬響應FeignClient嗎? 這個例子不到風度工作:Mock 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

Feign客戶端是接口。最好的方法通常是直接模擬接口。 – chrylis

回答

0

此刻,我知道2種好方法:

  1. 使用wiremock庫(春季引導我使用彈簧雲合同wiremock
  2. 的Mockito(我用@MockBean