我试图通过 mockito 模拟 restTemplate.exchange 方法,但无论我通过 mock 返回什么,它总是返回一个空值,即使我抛出异常:
这是实际的代码:
ResponseEntity<List<LOV>> response = restTemplate.exchange(url, GET, null,new ParameterizedTypeReference<List<LOV>>() {});
模拟代码:
ResponseEntity<List<LOV>> mockResponse = new ResponseEntity<List<LOV>>(mockLovList() ,HttpStatus.ACCEPTED);
Mockito.when(restTemplate.exchange(any(), eq(GET), any(), ArgumentMatchers.<ParameterizedTypeReference<List<LOV>>>any())).thenReturn(mockResponse);
每个参数在交换模拟中都是 ArgumentMatchers 类型,
mockLovList() 返回一个 LOV 列表
它应该返回我 mock 的任何东西,但它总是返回 null
最佳答案
这是一个 RestTemplate.exchange()
的工作示例模拟测试:
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.util.Arrays;
import java.util.List;
import static org.mockito.Mockito.*;
public class MyTest {
@Test
public void testRestTemplateExchange() {
RestTemplate restTemplate = mock(RestTemplate.class);
HttpEntity<String> httpRequestEntity = new HttpEntity<>("someString");
List<String> list = Arrays.asList("1", "2");
ResponseEntity mockResponse = new ResponseEntity<>(list, HttpStatus.ACCEPTED);
when(restTemplate.exchange(anyString(), any(), any(), any(ParameterizedTypeReference.class), any(Object[].class)))
.thenReturn(mockResponse);
final ResponseEntity<List<String>> exchange = restTemplate.exchange("/someUrl", HttpMethod.GET, httpRequestEntity, new ParameterizedTypeReference<List<String>>() {
});
Assert.assertEquals(list, exchange.getBody());
}
}
关于spring - mock resttemplate 交换总是返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55590669/