且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

RestTemplate模拟抛出NullPointerException

更新时间: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.