spring - mocking resttemplate exchange always returns null
问题描述
I'm trying to mock a restTemplate.exchange method through mockito but it always returns a null value no matter what i return through mock , even if i throw an exception:
this is the actual code :
ResponseEntity<List<LOV>> response = restTemplate.exchange(url, GET, null,new ParameterizedTypeReference<List<LOV>>() {});
mockito code:
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);
Every argument is of type ArgumentMatchers in the exchange mock , mockLovList() returns a list of LOV
it should return whatever i mocked , but it always returns 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());
}
}
推荐阅读
- python - 我的货币转换器应用程序有问题
- docker - docker run:invalid reference format error unbricking switch
- python - ImportError:无法从“tensorflow.python.keras.layers.normalization”导入名称“LayerNormalization”
- python - 将 BST 结果打印到 .txt 文件 - 写入问题
- laravel - Laravel 测试 csrf 不匹配
- javascript - querySelectorAll 以获取具有特定名称和值的输入滑块
- javascript - 检测div中的滚动结束
- oop - 为什么 SuperClass:initialize() 与 lua 中的 SuperClass.initialize(self) 不同?
- azure - @pandas_udf 给了我 SyntaxError
- python - 无论输入如何,SQLAlchemy 日期时间输入错误