2017-12-08 4 views
1

내 전체 응용 프로그램에 통합 테스트를 작성하고 하나의 특정 메서드를 모의하고 싶습니다 : RestTemplate 일부 데이터를 외부 웹 서비스로 보내고 응답을받는 데 사용합니다.RestTemplate의 웹 서비스 응답을 조롱하는 방법?

대신 로컬 파일에서 응답을 읽고 싶습니다 (외부 서버 응답을 모방하여 모방하므로 항상 동일합니다).

내 로컬 파일에는 생산시 외부 웹 서버가 응답하는 json/xml 응답 만 포함되어야합니다.

질문 : 어떻게 외부 xml 응답을 조롱 할 수 있습니까?

@Service 
public class MyBusinessClient { 
     @Autowired 
     private RestTemplate template; 

     public ResponseEntity<ProductsResponse> send(Req req) { 
       //sends request to external webservice api 
       return template.postForEntity(host, req, ProductsResponse.class); 
     } 
} 

@RunWith(SpringRunner.class) 
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 
public class Test { 

    @Test 
    public void test() { 
     String xml = loadFromFile("productsResponse.xml"); 
     //TODO how can I tell RestTemplate to assume that the external webserver responded with the value in xml variable? 
    } 
} 
+0

사용'MockRestServiceServer'는 https://stackoverflow.com/questions/42409768/how-to-mock-resttemplet-with-mockrestserviceserver 및 HTTPS를 참조하십시오. spring.io/spring/docs/5.0.2.RELEASE/spring-framework-reference/testing.html#spring-mvc-test-client –

답변

1

봄은 너무 중대하다 : // 문서 :

@Autowired 
    private RestTemplate restTemplate; 

    private MockRestServiceServer mockServer; 

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

    @Test 
    public void test() { 
     String xml = loadFromFile("productsResponse.xml"); 
     mockServer.expect(MockRestRequestMatchers.anything()).andRespond(MockRestResponseCreators.withSuccess(xml, MediaType.APPLICATION_XML)); 
    } 
+0

참조 : https://docs.spring.io/spring-boot/docs/ 현재/참조/html/boot-features-testing.html – slim

0

당신이를 위해 Mockito 같은 프레임 워크를 조롱 구현할 수 있습니다

when(restTemplate.postForEntity(...)) 
    .thenAnswer(answer(401)); 

와 같은 구현 뭔가 답 :

private Answer answer(int httpStatus) { 
    return (invocation) -> { 
     if (httpStatus >= 400) { 
      throw new RestClientException(...); 
     } 
     return <whatever>; 
    }; 
} 

그래서, 당신의 resttemplate에 당신이 가진 것 조롱

추후 읽기는 다음을 참조하십시오. Mockito

관련 문제