RestTemplate Mock throws NullPointerException

夙愿已清 提交于 2021-01-29 08:20:35

问题


I have a rest template that makes a call in a method in a service class like so:

public CustomerResponse someMethod() {
CustomerResponse response = restTemplate.exchange(url, HttpMethod.GET, null,  CustomerRes.class).getBody();
return response;
}

When trying to mock the restTemplate in my test class, it keeps throwing a NullPointerException on the line where the mock restTemplate is called:

public void checkResponseIsNotNull() {
CustomerResponse customerResponseMock = mock(CustomerResponse.class);
when(restTemplate.exchange(url, HttpMethod.GET, null, CustomerResponse.class).getBody()).thenReturn(customerResponseMock);
CustomerResponse cr = service.someMethod();
Assert.assertNotNull(cr);
}

Why is NullPointer being thrown? I have mocked a RestTemplate before, just without the getBody() method which leads be to believe its that which is causing the null pointer.


回答1:


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();

Originally you were setting-up the ResponseEntity only and the RestTemplate still remained with the defaults.. thus returning null when exchange has been called.



来源:https://stackoverflow.com/questions/53284914/resttemplate-mock-throws-nullpointerexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!