RestTemplate Junit:无法调用 "org.springframework.http.ResponseEntity.getBody()" 因为 "response" 为空

RestTemplate Junit: Cannot invoke "org.springframework.http.ResponseEntity.getBody()" because "response" is null

我有一个 spring 启动应用程序,它使用其余模板对其他内部项目造成 API 命中,它工作正常,我正在为它编写单元测试用例,但测试用例如果由于失败而失败抛出意外异常:java.lang.NullPointerException:无法调用“org.springframework.http.ResponseEntity.getBody()”,因为“响应”为空

服务

@Service
@Slf4j
public class DynamoDBServiceImpl implements DynamoDBService {

  private final RestTemplate restTemplate;
  private final HttpHeaders httpHeaders;
  private final String jwtHeader;
  private final String apiKeyHeader;
  private final String dynamodbSysApiKey;
  private final String fetchAdminGroupUrl;

  public DynamoDBServiceImpl(
      RestTemplate restTemplate,
      HttpHeaders httpHeaders,
      @Value("${header-name.jwt}") String jwtHeader,
      @Value("${header-name.api-key}") String apiKeyHeader,
      @Value("${dynamodb-sys-api-key}") String dynamodbSysApiKey,
      @Value("${dynamodb-fetch-admin-group-url}") String fetchAdminGroupUrl) {
    this.restTemplate = restTemplate;
    this.httpHeaders = httpHeaders;
    this.jwtHeader = jwtHeader;
    this.apiKeyHeader = apiKeyHeader;
    this.dynamodbSysApiKey = dynamodbSysApiKey;
    this.fetchAdminGroupUrl = fetchAdminGroupUrl;
  }

  @Override
  public List<AdminGroupDTO> getAllAdminGroups() {
    log.debug("Request to get admin group details with url : {}", fetchAdminGroupUrl);
    httpHeaders.set("Accept", MediaType.APPLICATION_JSON_VALUE);
    httpHeaders.setContentType(MediaType.APPLICATION_JSON);
    httpHeaders.setBearerAuth(CommonUtils.getHeaderFromCurrentHttpRequest(jwtHeader));
    httpHeaders.set(apiKeyHeader, dynamodbSysApiKey);

    HttpEntity<AdminGroupDTO> request = new HttpEntity<>(httpHeaders);
    ResponseEntity<List<AdminGroupDTO>> response =
        restTemplate.exchange(fetchAdminGroupUrl, HttpMethod.GET, request, new ParameterizedTypeReference<List<AdminGroupDTO>>() {});
    return response.getBody();
  }

}

测试

@SpringBootTest(classes = Application.class)
public class DynamoDBServiceTest {

  private final RestTemplate restTemplate = Mockito.mock(RestTemplate.class);
  private final HttpHeaders httpHeaders = new HttpHeaders();
  private final DynamoDBServiceImpl dynamoDBService =
      new DynamoDBServiceImpl(
          restTemplate, httpHeaders, "Authorization" , "Api-Key", "fake", "https://fake.com");

  @Test
  void testGetAllAdminGroups() {
    List<AdminGroupDTO> adminGroupDTOList = new ArrayList<>();
    AdminGroupDTO adminGroupDTO = new AdminGroupDTO();
    adminGroupDTO.setAdminGroupId(1L);
    adminGroupDTO.setAdminGroupName("fake");
    adminGroupDTO.setCountryName("fake");
    adminGroupDTOList.add(adminGroupDTO);

    ResponseEntity<List<AdminGroupDTO>> responseEntity = new ResponseEntity<>(adminGroupDTOList, HttpStatus.OK);
    when(restTemplate.exchange(
        ArgumentMatchers.anyString(),
        ArgumentMatchers.any(HttpMethod.class),
        ArgumentMatchers.any(),
        ArgumentMatchers.<Class<List<AdminGroupDTO>>>any()))
        .thenReturn(responseEntity);

    assertDoesNotThrow(dynamoDBService::getAllAdminGroups);
  }

}

替换这行代码:

 when(restTemplate.exchange(
        ArgumentMatchers.anyString(),
        ArgumentMatchers.any(HttpMethod.class),
        ArgumentMatchers.any(),
        ArgumentMatchers.<Class<List<AdminGroupDTO>>>any()))
        .thenReturn(responseEntity);

有了这个:

when(restTemplate.exchange(
            ArgumentMatchers.anyString(),
            ArgumentMatchers.any(HttpMethod.class),
            ArgumentMatchers.any(),
            ArgumentMatchers.eq(new ParameterizedTypeReference<List<AdminGroupDTO>>() {}))
    )
            .thenReturn(responseEntity);

异常应该消失。

有关详细信息,您可以查看 post。