如何模拟休息服务



我想知道如何模拟下面代码的剩余控制器

public void sendData(ID id, String xmlString, Records record) throws  ValidationException{
        ClientHttpRequestFactory requestFactory = new
                HttpComponentsClientHttpRequestFactory(HttpClients.createDefault());
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
        restTemplate.setMessageConverters(messageConverters);
        MultiValueMap<String,String> header = new LinkedMultiValueMap<>();
        header.add("x-api-key",api_key);
        header.add("Content-Type",content_type);
        header.add("Cache-Control",cache_control);
        HttpEntity<String> request = new HttpEntity<>(xmlString, header);
        try {
            restTemplate.postForEntity(getUri(id,record), request, String.class);
        }catch (RestClientResponseException e){
            throw new ValidationException("Error occurred while sending a file to some server "+e.getResponseBodyAsString());
        }
    }

任何建议都会有所帮助。我试图做这样的事情,

  @RunWith(MockitoJUnitRunner.class)
    public class Safe2RestControllerTest {
        private MockRestServiceServer server;
        private RestTemplate restTemplate;
        private restControllerClass serviceToTest;
     @Before
     public void init(){
    //some code for initialization of the parameters used in controller class
        this.server = MockRestServiceServer.bindTo(this.restTemplate).ignoreExpectOrder(true).build();
     }
      @Test
        public void testSendDataToSafe2() throws ValidationException, URISyntaxException {
        //some code here when().then()
        String responseBody = "{n" +
                    "    "responseMessage": "Validation succeeded, message 
                         accepted.",n" +
                    "    "responseCode": "SUCCESS",n" +
                    "    2"responseID": "627ccf4dcc1a413588e5e2bae7f47e9c::0d86869e-663a-41f0-9f4c-4c7e0b278905"n" +
                    "}";
        this.server.expect(MockRestRequestMatchers.requestTo(uri))
      .andRespond(MockRestResponseCreators.withSuccess(responseBody, 
       MediaType.APPLICATION_JSON));
        serviceToTest.sendDataToSafe2(id, xmlString, record);
        this.server.verify();
        }
    }

这是我要做的测试案例,但它仍然称为实际REST API

@jbnizet指出,您应该看一下MockRestServiceServer。它允许您测试使用RestTemplate进行HTTP调用的弹簧组件。

请参阅MockRestServiceserver和@RestClientTest。

相关内容

  • 没有找到相关文章

最新更新