RestTemplate模拟抛出NullPointerException

时间:2018-11-13 16:02:08

标签: java spring junit mocking mockito

我有一个rest模板,可以在服务类中的方法中进行如下调用:

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

尝试在测试类中模拟restTemplate时,它会在调用模拟restTemplate的行上不断抛出NullPointerException:

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

为什么会抛出NullPointer?我之前已经嘲笑过RestTemplate,只是没有getBody()方法,这导致人们相信它会导致空指针。

1 个答案:

答案 0 :(得分:1)

您应该再添加一个模拟级别:

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。