samedi 1 août 2020

Mockito thenReturn not working, returns Null

I am trying to mock the RestTemplate.exchange method. The main class is as follows:

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

public class JsonPlaceHolder {
    
    private RestTemplate restTemplate;

    public JsonPlaceHolder(RestTemplate restTemplate) {
        super();
        this.restTemplate = restTemplate;
    }

    
    public Post fetchPostEntity() {
        HttpHeaders headers = new HttpHeaders();
        Post reqPost = new Post();
        HttpEntity<Post> requestEntity = new HttpEntity<Post>(reqPost, headers);
        ResponseEntity<Post> respEntity = restTemplate.exchange("https://jsonplaceholder.typicode.com/posts/1",
                HttpMethod.GET, requestEntity, Post.class);
        System.out.println(respEntity);     
        return reqPost;     
    }
}

The post class is:

public class Post {
    private String userId;
    private String id;
    private String title;
    private String body;
    
    // Getters and Setters

    @Override
    public String toString() {
        return "Post [userId=" + userId + ", id=" + id + ", title=" + title + ", body=" + body + "]";
    }
    
}

To the test the above class I have the following code

@RunWith(MockitoJUnitRunner.class)
public class JsonPlaceHolderTest {
    
    @Mock
    private RestTemplate mockedRestTemplate;
    private String post1Uri = "https://jsonplaceholder.typicode.com/posts/1";

    
    
    @Test
    public void restTemplateExchange() {
        JsonPlaceHolder jsonPlaceHolder = new JsonPlaceHolder(mockedRestTemplate);
        
        Post fakePost = new Post();
        fakePost.setBody("BODY");
        fakePost.setId("44");
        fakePost.setUserId("USERID");
        fakePost.setTitle("TITLE");
        
        HttpHeaders headers = new HttpHeaders();
        
        Post reqPost = new Post();
        HttpEntity<Post> requestEntity = new HttpEntity<Post>(reqPost, headers);
        
        
        ResponseEntity<Post> fakeRespEntity = new ResponseEntity<Post>(fakePost, HttpStatus.OK);
        
        
        when(mockedRestTemplate.exchange(post1Uri, HttpMethod.GET, requestEntity, Post.class)).thenReturn(fakeRespEntity);
        
        Post respPost = jsonPlaceHolder.fetchPostEntity();
        
        System.out.println(respPost);
    }

}

The output is:

null
Post [userId=null, id=null, title=null, body=null]

Why isn't when().thenReturn() not working with RestTemplate.exchange(). I tried the similar thing with RestTemplate.getForEntity() and that works.

Aucun commentaire:

Enregistrer un commentaire