Класс тестирования JUnit:
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");
}
}
Тестируемый класс:
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;
}
}
Результат System.out.println(responseEntity);
равен null
.
Следует responseEntity
установить его смоделированное значение и вернуть (вместо текущего поведения, когда возвращается ноль), как настроено в: when(restTemplate.exchange("http://testing", HttpMethod.GET, entity, Resource.class)).thenReturn(responseEntity);
Так, когда c.getData("http://testing");
вызывается, смоделированный responseEntity
возвращается?
Вместо этого используйте обновление:
when(restTemplate.exchange(Matchers.eq("http://testing"), Matchers.eq(HttpMethod.GET), Matchers.isA(HttpEntity.class), Matchers.eq(Resource.class))).thenReturn(responseEntity);