java - 如何使用 RestTemplate 和 JUnit 测试 restclient?
问题描述
我是 JUNIT 的新手,并且RestTemplate
用来调用我的服务,我得到了 200 个响应。但是,我无法使用 JUnit 测试该类。尝试了不同的方法并获得 400 和 404。我想发布请求正文(json)并测试状态。如果有任何问题,请告诉我。
/**
* Rest client implementation
**/
public class CreateEmailDelegate implements CDM {
@Autowired
private RestTemplate restTemplate;
private String url = "http://example.com/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;
}
}
我的测试类返回 404 状态而不是 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.setContentType(MediaType.APPLICATION_JSON);
DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.wac);
this.mockMvc = builder.build();
}
public void testResponse() throws Exception, HttpClientErrorException, JsonProcessingException {
String url = "http://example.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
返回 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://example.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
集成测试。您既不能使用它来测试客户端实现。
如果您正在使用 Spring Boot,您可以使用另一种方法来实现您的目标,请参阅这个问题Spring boot testing of a rest client using @RestClientTest。
推荐阅读
- spring-boot - 如何在单列Spring数据MongoDB上应用两个条件语句
- java - 以反应方式从自定义杰克逊反序列化器中的数据库加载实体
- c# - 使用 RestSharp 从 API 返回 JSON 数据
- vba - 使用 ByRef 更新记录集字段
- python - 提取多个 XML 文件上所有标签之间的文本,并将提取的文本复制到 csv 文件
- laravel - 在 Laravel 和 Vue 之间共享数据的正确方式
- python - 如何在 tensorflow keras 中引用地面实况变量?
- hadoop - 无法将数据从 Pig 存储到 hbase
- reactjs - useForm隐藏的嵌套文件输入不起作用
- sql - 用单个列从另一个表更新一个表中的多个列?