How do I mock RestTemplate exchange using junit 5 (Jupiter)

Tags: , , , ,



I tried with below code but in response body I got empty records.

Please help me on below code.

Java Code:

    public Customer getCustomers(String customerId, String authorization) {

        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 Code:

    @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"));
        
    }

Answer

You need to set the value of customer in your response. The values you are setting in customer object is not being used anywhere. Try this:

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


Source: stackoverflow