JLo
JLo

Reputation: 7

How to mock restTemplate.postForEntity using Mockito

I have this in my service:

    private String postMethod(List<Integer> list) {
        String url = ...

        ResponseEntity<String> result = restTemplate.postForEntity(url, list, String.class);
        return result.getBody();
    }

In my test class I try to mock it like this:

    @Mock
    RestTemplate restTemplate;

    @Test
    public void methodTest() {
        List<Integer> list = new ArrayList<>(Arrays.asList(22234,9842234));
        when(restTemplate.postForEntity(anyString(), any(), eq(String.class))).thenReturn(new ResponseEntity<String>("5be9b7f2b7c", HttpStatus.OK));
        String result = enrollmentServiceClient.retry(list);

        assertEquals("5be9b7f2b7c", result);
    }

When I run my test I get a null pointer exception. Does anyone know why it is not returning the ResponseEntity?

Looks like this is the method I should be mocking:

public ResponseEntity postForEntity(URI url, @Nullable Object request, Class responseType)

Upvotes: 0

Views: 2568

Answers (1)

Eugene
Eugene

Reputation: 5985

  1. Test must be annotated with @RunWith(MockitoJUnitRunner.class). This annotation automatically initializes mocks annotated with @Mock. In case you have used JUnit 5 you must use @ExtendWith({MockitoExtension.class}) instead.

  2. RestTemplate mock should be injected into the service under the test. You need to create a constructor for EnrollmentServiceClient service with RestTemplate parameter. RestTemplate mock can be injected into service via @InjectMocks annotation

Example of working test:

@RunWith(MockitoJUnitRunner.class)
public class TestClass {
    @Mock
    RestTemplate restTemplate;

    @InjectMocks
    EnrollmentServiceClient enrollmentServiceClient;

    @Test
    public void methodTest() {
        List<Integer> list = new ArrayList<>(Arrays.asList(22234,9842234));
        when(restTemplate.postForEntity(anyString(), any(), eq(String.class))).thenReturn(new ResponseEntity<String>("RESULT", HttpStatus.OK));
        String result = enrollmentServiceClient.retry(list);

        assertEquals("RESULT", result);
    }
}

public class EnrollmentServiceClient {
    RestTemplate restTemplate;

    public EnrollmentServiceClient(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    private String postMethod(List<Integer> list) {
        String url = "...";
        ResponseEntity<String> result = restTemplate.postForEntity(url, list, String.class);
        return result.getBody();
    }

    public String retry(List<Integer> list) {
        return postMethod(list);
    }
}

Upvotes: 1

Related Questions