如何模拟客户端休息服务



我正在尝试为下面的REST API创建Mockito Test Run是控制器类,然后是模拟测试,我要执行该测试,但问题是它仍在调用实际REST API而不是嘲笑它,

1)控制器类

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());
        }
    }

2)测试类

     @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.sendData(id, xmlString, record);
            this.server.verify();
            }
        }

我应该如何继续,任何建议都将不胜感激。

春季的MVC测试设备使它非常容易。

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = YourController.class)
public class YourControllerTest {
    @Autowired
    private MockMvc mockMvc;
    @Test
    public void testSendDataToSafe2() throws Exception {
        // prepare e.g. create the requestBody
        MvcResult mvcResult = mockMvc.perform(post(uri).contentType(MediaType.APPLICATION_JSON).content(requestBody))
            .andExpect(status().isOk())
            .andReturn();
        Assert.assertEquals(responseBody, mvcResult.getResponse().getContentAsString());
    }
}

有关更多详细信息,请参见标题为" 添加单元测试"的部分,此处和/或标题为" 自动配置的Spring MVC Tests "部分。

您的问题还指出:"问题是仍在调用实际的REST API",因此我猜想,除了调用您的控制器是一个测试上下文之外,您还希望嘲笑该控制器的某些行为。具体来说,您想模拟该控制器中使用的RestTemplate实例。如果是这样,则必须更改控制器实现,以使RestTemplate实例是@Autowired类成员。然后,您会在测试案例中声明一个模拟:

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = YourController.class)
public class YourControllerTest {
    @Autowired
    private MockMvc mockMvc;
    @MockBean
    private RestTemplate restTemplate;
    @Test
    public void testSendDataToSafe2() throws Exception {
        // prepare e.g. create the requestBody
        // tell your mocked RestTemplate what to do when it is invoked within the controller
        Mockito.when(restTemplate.postForEntity(..., ..., ...)).thenReturn(...);
        MvcResult mvcResult = mockMvc.perform(post(uri).contentType(MediaType.APPLICATION_JSON).content(requestBody))
            .andExpect(status().isOk())
            .andReturn();
        Assert.assertEquals(responseBody, mvcResult.getResponse().getContentAsString());
    }
}

上述代码对spring-test:4.3.10.RELEASE有效。

最新更新