本文介绍了如何使用RestTemplate和JUnit测试restclient?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JUNIT的新手,并且使用RestTemplate来调用我的服务,我得到200相同的响应.但是,我无法使用JUnit测试该类.尝试了不同的方法,并获得了400和404.我想发布请求正文(json)并测试状态.请让我知道是否有任何问题.

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

我的Test类,它返回404状态而不是200状态

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

使用TestRestTemplate代替MockMvc的我的Test类返回400

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

推荐答案

我认为您正在尝试实施集成测试而不是单元测试,两者之间存在很大的差异. MockMvc用于实现单元测试,而TestRestTemplate用于集成测试.您既不能使用它来测试客户端实现.

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.

请参见 Spring Boot中的单元和集成测试

如果您正在使用Spring Boot,则可以使用另一种方法来实现您的目标,请参见以下问题使用 @@对其余客户端进行春季启动测试 RestClientTest .

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.

这篇关于如何使用RestTemplate和JUnit测试restclient?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 05:22