我正在尝试模拟 restClient 外部 API,但它正在调用实际的 API 而不是模拟它。请提供帮助,因为我不确定我哪里出错了。
我尝试嘲笑电话和其他一些事情,但没有奏效。
public class TestService
{
private static final String EXTERNAL_API = "http://LinktoExternalAPI/";
@Autowired
RestTemplate restTemplate;
public Map<String, String> countryCodes()
{
Map<String, String> map = new TreeMap<>();
try
{
ResponseEntity<testCountry[]> responseEntity = restTemplate
.getForEntity(EXTERNAL_API
, testCountry[].class);
List<testCountry> testCountryList = Arrays.asList(responseEntity.getBody());
map = testCountryList.stream()
.collect(Collectors.toMap(testCountry::getCode, testCountry::getName));
}
catch (HttpClientErrorException | HttpServerErrorException httpClientOrServerExc)
{
}
return map;
}
}
测试用例如下:
@RunWith(PowerMockRunner.class)
public class TestServiceTest
{
@InjectMocks
TestService testService;
@Mock
RestTemplate restTemplate;
private static final String EXTERNAL_API = "http://LinktoExternalAPI/";
@Test
public void testCountryCodes(){
TestCountry testCountry = new TestCountry();
testCountry.setCode("JPN");
testCountry.setName("Japan");
List<testCountry> testCountryList = new ArrayList<testCountry>();
testCountryList.add(testCountry);
Mockito.when(restTemplate.getForEntity(EXTERNAL_API, testCountry[].class)).thenReturn(new ResponseEntity(testCountryList, HttpStatus.OK));
Map<String, String> result = testService.countryCodes();
// result is pulling the actual size of the api instead of mocking and sending me testCountryList size.
<Will mention assertion here>
}
结果是拉取 API 的实际大小,而不是模拟并发送给我testCountryList
大小。