Spring Boot Junit对putMapping的测试始终返回null

时间:2019-04-22 15:56:23

标签: spring-boot junit spring-boot-test

我有一个PutMapping,它将首先检查Reward-Entity,然后如果存在,它将进一步继续更新Entity

@PutMapping
public ResponseEntity<RewardResponse> updateValidReward(Principal updatedPrincipal,
                                                                @RequestBody RewardUpdateRequest rewardUpdateRequest) {

            Optional<RewardEntity> rewardEntityInDatabase =
                RewardService.getRewardById(rewardUpdateRequest.getRewardId());

        if (!rewardEntityInDatabase.isPresent()) {
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }

        RewardEntity updatedReward = updateReward(updatedPrincipal,
                rewardUpdateRequest, rewardEntityInDatabase.get());

        RewardResponse updatedRewardResponse = RewardResponse.builder()
                .reward(RewardMapper.fromRewardEntity(updatedReward))
                .build();

        return ResponseEntity.ok(updatedRewardResponse);
}

当我尝试以以下格式为此编写Test-case时,这对我来说是一个挑战

ResponseEntity<RewardResponse> rewardResponse =
                controller.updateValidReward(principal, rewardUpdateRequest);


        RewardApi rewardApiToValidate = rewardResponse.getBody().getReward();
        assertThat(rewardApiExpected.getRewardTitle()).isEqualTo(rewardApiToValidate.getRewardTitle());
        assertThat(rewardApiExpected.getRewardText()).isEqualTo(rewardApiToValidate.getRewardText());

执行测试代码中的以下行时,我总是得到NullPointerException

rewardResponse.getBody().getReward();

因为实际代码中的以下条件始终变为true,并且始终返回HttpStatus.NOT_FOUND

if (!rewardEntityInDatabase.isPresent()) {
                    return new ResponseEntity<>(HttpStatus.NOT_FOUND);
            }

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我通过完全调用原始代码中的Controller来解决此问题。首先,我通过测试代码调用了Optional --> getRewardIdFromDatabase()代码,执行了Controller的update方法