如何使用Junit 5(Jupiter)模拟RestTemplate交换

时间:2018-11-14 09:48:18

标签: java unit-testing spring-boot mockito junit5

我尝试使用以下代码,但在响应正文中,我得到了空记录。

请帮助我处理以下代码。

**Java Code:-**

public Customer getCustomers(字符串customerId,字符串授权){

    MultiValueMap<String, String> headers=new LinkedMultiValueMap<>();
    headers.set("Authorization",authorization);
    HttpEntity<Customer> request=new HttpEntity<>(headers);
    Map<String, Object> params = new HashMap<>();
    params.put("CustomerId", customerId);
    String url=https://localhost:8080/api/customer/{CustomerId}/get;
    ResponseEntity<Customer> response =restTemplate.exchange(url, HttpMethod.GET, request, Customer.class,params);
    Customer customer=null;
    if(response!=null && response.getBody()!=null) {
        customer= response.getBody();
    }
    return customer;}

测试用例-

@Test
public void testGetCustomersSuccess() {
    Customer customer = new Customer();
    customer.setCountryCode("countryCode");
    customer.setCreatedFrom("createdFrom");
    customer.setCustomerlandline("224153");
    customer.setCustomermobile("1522252");
    customer.setEmail("email");
    customer.setFirstname("firstName");
    customer.setFiscalCode("fiscalCode");
    customer.setFirstname("lastName");
    customer.setId("5");
    MultiValueMap<String, String> headers=new LinkedMultiValueMap<>();
    headers.set(Authorization,"12152");
    ResponseEntity<Customer> response=new ResponseEntity<Customer>(HttpStatus.OK);
    when(restTemplate.exchange(Mockito.any(String.class),
            Mockito.<HttpMethod> any(),
            Mockito.<HttpEntity<Customer>> any(),
            Mockito.<Class<Customer>> any(),
            Mockito.<String, Object> anyMap()))
    .thenReturn(response);
    assertEquals(response.getBody(),serviceClientImpl.getCustomers("5", "12152"));

}

1 个答案:

答案 0 :(得分:1)

您需要在响应中设置客户的价值。 您在客户对象中设置的值未在任何地方使用。 试试这个:

ResponseEntity<Customer> response=new ResponseEntity<Customer>(customer,HttpStatus.OK);