Issue
My Service class is below, followed by its test -
@Service
public class MyServiceImpl implements MyService {
@Autowired
private RestTemplate restTemplate;
@Override
public StudentInfo getStudentInfo(String name) {
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
HttpEntity entity = new HttpEntity(headers);
StudentInfo student = null;
URI uri = new URI("http:\\someurl.com");
ResponseEntity<String> responseEntity = restTemplate.exchange(uri,
HttpMethod.GET, entity,
String.class);
if (responseEntity.getStatusCode().equals(HttpStatus.NO_CONTENT)) {
throw new Exception("Student absent");
}else {
ObjectMapper mapper = new ObjectMapper();
StudentInfo student = mapper.readValue(responseEntity.getBody(), StudentInfo.class);
}
return student;
}
}
Test class: In my test class below, I see ResponseEntity object as null while debugging which causes a NPE.
@RunWith(MockitoJUnitRunner.class)
public class MyServiceImplTest {
@InjectMocks
private MyService service = new MyServiceImpl();
@Mock
private RestTemplate restTemplate;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testStudentGetterResponse() {
ResponseEntity<String> mockEntity = Mockito.spy(new ResponseEntity({"id" : 1, "name" : "Rutzen"}, HttpStatus.OK));
doReturn(mockEntity).when(restTemplate).exchange(any(URI.class), any(HttpMethod.class), any(ResponseEntity.class),
any(Class.class));
StudentInfo info = service.getStudentInfo("testuser");
Assert.assertNotNull(info);
}
}
When I debug the test, I get a null value for responseEntity at the following line in the main service class -
ResponseEntity<String> responseEntity = restTemplate.exchange(uri,
HttpMethod.GET, entity,
String.class);
Solution
This instruction ...
doReturn(mockEntity).when(restTemplate).exchange(
any(URI.class),
any(HttpMethod.class),
any(ResponseEntity.class),
any(Class.class)
);
... should be replaced with:
doReturn(mockEntity).when(restTemplate).exchange(
any(URI.class),
any(HttpMethod.class),
any(HttpEntity.class),
any(Class.class)
);
Because getStudentInfo()
creates an instance of HttpEntity
(not ResponseEntity
) which is then passed to the restTemplate.exchange()
invocation.
Answered By - glytching