尝试测试代表Rest Client的类时遇到问题。我在Spring Boot中使用RestTemplate。
这是抽象的RestClient类:
public abstract class RestClient {
...
public RestResponse sendPostRequest(URI baseUri, String resource, IRestRequest restRequest, ClassresponseClass)
throws ServerException, ClientException {
...
try {
RestTemplate restTemplate = new RestTemplate();
response = restTemplate.exchange(baseUri, HttpMethod.POST, getEntity(restRequest), responseClass);
result = response.getBody();
getLogger().debug("[{}] received", result);
return result;
} catch (HttpClientErrorException e) {
throw new ClientException(e.getCause());
} catch (HttpServerErrorException e) {
throw new ServerException(e.getCause());
} catch (Exception e) {
getLogger().error("Error with cause: {}.", e.getMessage());
}
...
}
}
这是实际的实现:
public class ActualRestClient extends RestClient {
public RestResponse sendFetchFileRequest(URI baseUri, FetchFileRequest request) throws ServerException, ClientException {
return sendPostRequest(baseUri, "FETCH_FILE", request, RestResponse.class);
}
}
这是测试:
@RunWith(PowerMockRunner.class)
@PrepareForTest({ActualRestClient.class, RestClient.class})
public class ActualResRestClientTest {
private static final String REQUEST_URI = "something";
@InjectMocks
public ActualRestClient testee;
@Mock
private RestTemplate restTemplate;
@Test(expected = ServerException.class)
public void sendPostRequestWithResponseBody_throwsServerException() throws Exception {
HttpServerErrorException httpServerErrorException = new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR);
when(restTemplate.exchange(Mockito.any(URI.class), eq(HttpMethod.POST), Mockito.any(), eq(FetchFileRequest.class))).thenThrow(httpServerErrorException);
testee.sendFetchFileRequest(new URI(REQUEST_URI), new FetchFileRequest());
}
}
ClientException和ServerException是我通过扩展Exception类创建的异常。 我的问题是,在RestClient类中捕获了另一个异常(消息:“ URI不是绝对的”),而不是HttpServerErrorException,我不明白为什么。谢谢!
答案 0 :(得分:3)
正如评论者已经表达的那样:做new URI("something")
已经扔给了你。但是,即使您传递了一个“有效的” URI,您的代码也将无法正常工作,因为这会给您带来误解。您会看到:
RestTemplate restTemplate = new RestTemplate();
response = restTemplate.exchange(baseUri, HttpMethod.POST, getEntity(restRequest), responseClass);
该代码存在于被测类的方法中。但是@InjectMocks仅适用于类的 fields 。
换句话说:执行生产代码时,将创建一个 new (完全不同的**)ResponseTemplate实例。因此,您的模拟规范是无关紧要的,因为不会在您的方法上调用该方法首先模拟。
两个选择:
new()
的调用。我建议您宁愿使用选项一,而避免完全使用PowerMock(ito)扩展!