背景
在测试Spring RestTemplate的时候,为了规避上下文带来的影响且保证单元测试的效率与独立性,使用mock技术是常用的手法。但是实际项目中,如果要从RestTemplate转为其他框架的时候,就需要修改所有的单元测试代码,也就是说,目前的代码还是依赖于框架的,还是不够独立:
public class SpringCloudRefactoringTest {
private static final Long EXISTING_VARIA = 1L;
private static final Map<String, Long> GOOD_HTTP_PARAMS = Collections.singletonMap("id", EXISTING_VARIA);
private static final Long NON_EXISTING_VARIA = 15123123L;
private static final Map<String, Long> NON_EXISTING_HTTP_PARAMS = Collections.singletonMap("id", NON_EXISTING_VARIA);
private static final Long OVER_VARIA = 99999999L;
private static final Map<String, Long> BAD_HTTP_PARAMS = Collections.singletonMap("id", BAD_VARIA);
private static final ResponseEntity<SpringCloudResponse> ERROR_RESPONSE =
new ResponseEntity<>(new SpringCloudFactResponse("NoSuchQuoteException", "No quote with id=15123123."), HttpStatus.OK);
private static final ResponseEntity<SpringCloudFactResponse> ITEM_RESPONSE =
new ResponseEntity<>(new SpringCloudFactResponse("success", new SpringCloudFact(1L, "OK")), HttpStatus.OK);
@Test
public void serviceShouldReturnFact() {
RestTemplate restTemplate = mock(RestTemplate.class);
when(restTemplate.getForEntity(FACT_URL, SpringCloudFactResponse.class, GOOD_HTTP_PARAMS))
.thenReturn(ITEM_RESPONSE);
SpringCloudService myServiceUnderTest =