How to test restclient using RestTemplate and JUnit?

柔情痞子 提交于 2019-12-11 06:32:28

问题


I am new to JUNIT and using RestTemplate to call my service, I'm getting 200 response for the same. But, I can't test the class using JUnit. Tried different approaches and getting 400 and 404. I want to post the request body (json) and test the status. Please let me know if there is any issue.

/**
* Rest client implementation
**/  
public class CreateEmailDelegate implements CDM {

    @Autowired
    private RestTemplate restTemplate;
    private  String url = "http://communication-svc-dvnt-b.test.sf.com/CDM-Service-1.0.0/communications/emails";

    public ResponseEntity<CDResponse> createEmail(CDMEmailRequest cDRequest) throws UnavailableServiceException, InvalidInputException {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("SR_API_Key", SR_API_KEY);
        httpHeaders.set("consumerIdentification", CONSUMER_IDENTIFICATION);
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);         
        HttpEntity< CDMEmailRequest > cDRequestEntity = new HttpEntity<>( cDRequest, httpHeaders);  
        ResponseEntity< CDResponse > cDResponse = null;

        try {
            cDResponse = restTemplate.postForEntity(url, cDRequestEntity, CDResponse.class);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            throw  e;       
        }

        return cDResponse;
    }
}  

My Test class which return 404 status instead of 200

    @RunWith(SpringJUnit4ClassRunner.class)
    public class CreateEmailCommunicationDelegateTest {

        @Before
        public void setup() {
            httpHeaders = new HttpHeaders();
            httpHeaders.set("SR_API_Key", SR_API_KEY);
            httpHeaders.set("consumerIdentification", CONSUMER_IDENTIFICATION);
            httpHeaders.set("X_SF_Transaction_Id", X_SF_Transaction_Id);
            httpHeaders.setContentType(MediaType.APPLICATION_JSON);
            DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.wac);
            this.mockMvc = builder.build();
        }


        public void testResponse() throws Exception, HttpClientErrorException, JsonProcessingException {
            String url = "http://communication-svc-dvnt-b.test.statefarm.com/CommunicationDeliveryManagement-Service-1.0.0/communications/emails";

            CDMEmailRequest anObject = new CDMEmailRequest();
            ResultMatcher ok = MockMvcResultMatchers.status().isOk();
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
            ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
            String requestJson = ow.writeValueAsString(anObject);

            System.out.println(requestJson);
            MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post(url).contentType(MediaType.APPLICATION_JSON_UTF8).content(requestJson);
            this.mockMvc.perform(builder).andExpect(ok).andDo(MockMvcResultHandlers.print());
        }
    } 

My Test class using TestRestTemplate instead MockMvc returns 400

@RunWith(SpringJUnit4ClassRunner.class)
public class CreateEmailCommunicationDelegateTest {

    @Before
    public void setup() {
        httpHeaders = new HttpHeaders();
        // rest headers as above
    }

    @Test
    public void testResponse() throws Exception, HttpClientErrorException, JsonProcessingException {

        String url = "http://communication-svc-dvnt-b.test.statefarm.com/CommunicationDeliveryManagement-Service-1.0.0/communications/emails";

        String username = "";
        String password = "";
        HttpEntity<CDMEmailRequest>
                cDEntity = new HttpEntity<>(httpHeaders);

        restTemplate = new TestRestTemplate(username, password);

        responseEntity =
                restTemplate.exchange(url, HttpMethod.POST, cDEntity,
                        CDResponse.class);

        assertNotNull(responseEntity);
        assertEquals(HttpStatus.OK,
                responseEntity.getStatusCode());
    }
} 

回答1:


I think you're trying to implement an integration test instead of an unit test, there is quite difference. MockMvc should be used to implement unit tests and TestRestTemplate for integration tests. You can't neither use it for testing a Client implementation.

See Unit and Integration Tests in Spring Boot

If you are working with Spring Boot you could achieve your goal using another approach see this question Spring boot testing of a rest client using @RestClientTest.



来源:https://stackoverflow.com/questions/57013137/how-to-test-restclient-using-resttemplate-and-junit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!