【发布时间】:2019-06-06 03:24:03
【问题描述】:
我尝试为调用第 3 方 api 的服务中的其余调用编写测试用例。
@RunWith(MockitoJUnitRunner.class)
public class ForceServiceTest {
private ForceService forceService;
@Mock
private ForceServiceConfig config;
@Mock
private RestTemplate restTemplate;
@Before
public void setup() {
forceService = new ForceService(config);
}
@Test
public void apiCall_valid() throws JSONException {
HttpHeaders headers = new HttpHeaders();
headers.set(CONTENT_TYPE, "application/x-www-form-urlencoded");
headers.set(ACCEPT, APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>(
"id=null",
headers);
config.authTokenUrl = "https://ex...com/..";
Mockito.when(restTemplate.exchange(config.authTokenUrl, HttpMethod.POST, entity, Access.class)).thenReturn(null);
// Mockito.when(any()).thenReturn(null);
forceService.apiCall();
}
}
@Component
public class ForceService {
private ForceServiceConfig config;
private RestTemplate restTemplate = new RestTemplate();
public ForceService(ForceServiceConfig config) {
this.config = config;
}
private String apiCall() {
HttpHeaders headers = new HttpHeaders();
headers.set(CONTENT_TYPE, "application/x-www-form-urlencoded");
headers.set(ACCEPT, APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>(
"&id=" + config.id,
headers);
ResponseEntity<Access> response = restTemplate.exchange(config.authTokenUrl, HttpMethod.POST, entity,
Access.class);
return response.getBody().token_type + " " + response.getBody().access_token;
}
}
我收到以下错误:
org.springframework.web.client.HttpClientErrorException: 404 Not Found 在 org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:78) 在 org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700) 在 org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653)
它正在调用测试类中的 api,我不希望发生这种情况。 我需要模拟 3rd 方 api 的 resttemplate 调用。我怎么能在不实际调用 api 的情况下做到这一点?
【问题讨论】:
-
老实说,它不应该在没有明确配置的情况下调用任何东西,因为它是 MOCK,所以没有实现underneth并且会返回(就像你说你想要的那样)
-
我建议wiremock.org
标签: maven unit-testing spring-boot resttemplate spring-test