我有一个休息模板,它在服务类中的方法中进行调用,如下所示: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 回答
慕盖茨4494581
TA贡献1850条经验 获得超11个赞
您应该再添加一层模拟:
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 。
添加回答
举报
0/150
提交
取消