Issue
JUnit test class :
public class TestingClass {
@Mock
private RestTemplate restTemplate;
@Mock
private HttpEntity entity;
@Mock
private ResponseEntity<Resource> responseEntity;
@Before
public void setup() {
MockitoHelper.initMocks(this);
}
@Test
public void getDataTest() {
ClassToTest c = new ClassToTest(restTemplate);
when(restTemplate.exchange("http://testing", HttpMethod.GET, entity, Resource.class)).thenReturn(responseEntity);
c.getData("http://testing");
}
}
Class being tested :
import org.jsoup.helper.Validate;
import org.springframework.core.io.Resource;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import java.io.InputStream;
import java.util.Optional;
public class ClassToTest {
private HttpHeaders headers;
private RestTemplate restTemplate;
public ClassToTest(RestTemplate restTemplate){
this.restTemplate = restTemplate;
headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
}
public Optional<InputStream> getData(final String mediaUrl) {
Validate.notEmpty(mediaUrl);
final String requestJson = "{}";
final HttpEntity<String> entity = new HttpEntity<>(requestJson, headers);
Optional inputStreamOptional = Optional.empty();
try {
final ResponseEntity<Resource> responseEntity = restTemplate.exchange(mediaUrl, HttpMethod.GET, entity, Resource.class);
System.out.println(responseEntity);
} catch (Exception exception) {
exception.printStackTrace();
}
return inputStreamOptional;
}
}
The result of System.out.println(responseEntity);
is null
.
Should responseEntity
be set to it's mocked value and returned (instead of current behavior where null is returned) as is configured in : when(restTemplate.exchange("http://testing", HttpMethod.GET, entity, Resource.class)).thenReturn(responseEntity);
So when c.getData("http://testing");
is invoked the mocked responseEntity
is returned ?
Update use instead :
when(restTemplate.exchange(Matchers.eq("http://testing"), Matchers.eq(HttpMethod.GET), Matchers.isA(HttpEntity.class), Matchers.eq(Resource.class))).thenReturn(responseEntity);
Solution
It's most likely returning null because your parameter definition in when
and the actual parametes differ. In your case it's very likely that your mocked entity
and the HttpEntity
you're creating in your code under test are neither the same nor equal. So you need to widen your expectations in the when
-definition. You should use Matchers in your definition and the could use isA(HttpEntity.class)
for your entity.
Answered By - Nicktar
Answer Checked By - Gilberto Lyons (JavaFixing Admin)