更新时间:2023-11-19 14:36:58
您应该再添加一个模拟级别:
You should add one more level of mocking:
CustomerResponse customerResponseMock = mock(CustomerResponse.class);
ResponseEntity reMock = mock(ResponseEntity.class);
when(reMock.getBody()).thenReturn(customerResponseMock);
when(restTemplate.exchange(url, HttpMethod.GET, null, CustomerResponse.class)).thenReturn(reMock);
CustomerResponse cr = service.someMethod();
最初,您只设置了ResponseEntity
,而RestTemplate
仍保留默认设置..因此,在调用exchange
时返回null.
Originally you were setting-up the ResponseEntity
only and the RestTemplate
still remained with the defaults.. thus returning null when exchange
has been called.