java - 模拟对象返回 null
问题描述
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
设置为它的模拟值并返回(而不是返回 null 的当前行为),如在中配置的: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);
解决方案
它很可能返回 null 因为您的参数定义when
和实际参数不同。entity
在您的情况下,您的模拟和HttpEntity
您在被测代码中创建的很可能既不相同也不相等。所以你需要扩大你对when
-definition 的期望。您应该在定义中使用 Matchers 并且可以isA(HttpEntity.class)
用于您的实体。
推荐阅读
- ssh - ssh permission denied when prefixing with ssh protocol
- azure - How to redirect traffic hosted on an azure endpoint (DNS/static IP) to different external IP address
- download - ionic4/Angular7 - Property 'dataDirectory' does not exist on type 'File'
- mysql - 我无法通过 PHPMyAdmin 导入数据库
- android - Android Pie 中是否存在用于 NFC 标签连接的错误?
- vue.js - How do I add dynamic data to apexcharts using vue.js?
- bash - 使用带有 FIFO 的 netcat
- gitlab - How can add SSH key in gitlab?
- javascript - CookieService 的 StaticInjectorError
- php - GET request works with CURL but not as a URL