RestTemplate 模拟抛出 NullPointerException

我有一个休息模板,它在服务类中的方法中进行调用,如下所示:


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() 方法,这导致人们相信它是导致空指针的原因。


莫回无
浏览 665回答 1
1回答

慕盖茨4494581

您应该再添加一层模拟: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 。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java