Search code examples
javaspringresttemplatejunit5

ResponseEntity Coming as null in Resttemplate JUNIT Call


Writing JUNIT-5 for a GET REST Call My actual implementation is like below and its working fine.

ResponseEntity<OrderDocument> responseEntity = restTemplate.exchange(
URL,HttpMethod.GET,new HttpEntity<>(headers),OrderDocument.class,
message.getPayload().toString());
responseEntity.getBody() // Null pointer Exception when calling from JUNIT

My Full implementation of JUNIT is below

@SpringBootTest
@ActiveProfiles("test")
class OrderMasterClientImplTest {

@Autowired
OrderMasterClientImpl orderMasterClient;
private ConsumerMessage consumerMessage;
private EventMessage eventMessage;

@MockBean
@Qualifier("orderMasterRestTemplate")
private RestTemplate restTemplate;

@MockBean
ResponseEntity responseEntity;

@BeforeEach
public void setUp() throws Exception {
    ObjectMapper objectMapper= new ObjectMapper();
    eventMessage = objectMapper.readValue(
            this.getClass().getClassLoader().getResourceAsStream(
                    "event_message.json"),
            EventMessage.class);
    System.out.println( " "+eventMessage.getOrderId());
    consumerMessage = new ConsumerMessage(eventMessage);
    System.out.println( " consumerMessage "+consumerMessage.getPayload());

}
@Test
void consume() {

    when(restTemplate.exchange(anyString() , any(HttpMethod.class)   ,  
any(HttpEntity.class) ,any(Class.class) , any(String.class) 
)).thenReturn(responseEntity);

    System.out.println( " consumerMessage "+consumerMessage.getPayload());
    OrderDocument orderDocumentactual = 
orderMasterClient.consume(consumerMessage);

    Assertions.assertNotNull(orderDocumentactual);
}

}

What is the mistake i am doing . Please help.


Solution

  • Testing in this fashion with mocking a restTemplate can lead to unexpected behaviour when the server returns anything other than an actual successfull response. I'd recommend using MockRestServiceServer as this provides for better testing.

    If you do want to continue the current approach - you seem to be returning a responseEntity which is a mock created by the @MockBean annotation. I don't see any code in your question which defines how that mock will behave when someone calls a getBody() on it. That could be something to look at. You could either define a real ResponseEntity to be returned in your mock, or mock all interactions with responseEntity.