我正在尝试模拟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
大小。
调用实际API的原因可能是您要模拟的URL与运行时生成的URL不完全相同,因此找不到模拟并调用实际的API。在这种情况下,可以使用Mockito.any()
。
所以模拟代码将为Mockito.when(restTemplate.getForEntity(Mockito.any(), Mockito.any())).thenReturn(new ResponseEntity(testCountryList, HttpStatus.OK));
@RunWith(MockitoJUnitRunner.class)
public class TestServiceTest {
@InjectMocks
private TestService testService;
@Mock
private RestTemplate restTemplate;
@Test
public void testCountryCodes(){
TestCountry testCountry = new TestCountry();
testCountry.setCode("JPN");
testCountry.setName("Japan");
TestCountry[] testCountryList = {
testCountry
};
Mockito.when(restTemplate.getForEntity(Mockito.anyString(), Mockito.any())).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.
}
}
也尝试使用@RunWith(MockitoJUnitRunner.class)
而不是PowerMockRunner.class
,因为您似乎不需要PowerMock功能。
您在嘲笑错误的方法定义。
您需要定义this
方法的行为。
this
有关更完整的示例,请查看我的答案Mockito.when(api.getForObject(any(String.class),any(Class.class), ArgumentMatchers.<Object>any())).thenReturn(obj1);
。