spring 模拟restTemplate返回空值

ncgqoxb0  于 2023-01-29  发布在  Spring
关注(0)|答案(1)|浏览(230)

由于某种原因,下面的测试失败了,因为“response”为空,但它不应该为空,因为我使用when()函数返回了一个初始化的对象。

Cannot invoke "org.springframework.http.ResponseEntity.getBody()" because "response" is null
java.lang.NullPointerException: Cannot invoke "org.springframework.http.ResponseEntity.getBody()" because "response" is null

这是测试类:

class UtilsControllerTest {

    @Mock
    RestTemplate restTemplate=mock(RestTemplate.class);
    @Test
    void checkPermission() {
        boolean permitted = true;

        ResponseEntity<PermissionResponseModel> response = ResponseEntity.ok(new PermissionResponseModel(permitted));

        when(restTemplate.postForEntity(any(String.class), any(Map.class), any(Class.class)))
                .thenReturn(response);

        UtilsController utilsController = new UtilsController();
        assertTrue(utilsController.checkPermission("69696969", Task.MAKE_REQUEST, restTemplate));
        verify(restTemplate, times(1)).postForEntity(any(), any(), any());
    }

}

这是UtilsController的实现:

public class UtilsController {
    private static final String authString = "Authorization";

    /**
     * Checks if the user is authorised to do a certain task.
     *
     * @param token the identification token
     * @param task  the task
     * @return true iff user is allowed, false otherwise
     */
    public boolean checkPermission(String token, Task task, RestTemplate restTemplate) {
        HttpHeaders authHeaders = new HttpHeaders();
        authHeaders.setContentType(MediaType.APPLICATION_JSON);
        authHeaders.set(authString, token);
        String url = "http://localhost:8081/permission";

        PermissionRequestModel prm = new PermissionRequestModel();
        prm.setTask(task);
        HttpEntity<PermissionResponseModel> entity = new HttpEntity(prm, authHeaders);

        ResponseEntity<PermissionResponseModel> response =
                restTemplate.postForEntity(url, entity, PermissionResponseModel.class);
        return response.getBody().isPermitted();
    }
}

我试着模拟返回的响应实体,它也不工作。仍然,响应是空的。但是在这两种情况下,当我调试它,响应有正确的值,不是空的。

1l5u6lss

1l5u6lss1#

正如M.代努姆所说,我正在为另一个postForEntity方法注册该行为。

when(restTemplate.postForEntity(anyString(), any(HttpEntity.class), any(Class.class)))
                .thenReturn(new ResponseEntity<>(new PermissionResponseModel(permitted), HttpStatus.OK));

相关问题