Search code examples
spring-bootjunitspring-boot-test

Spring boot Junit testing for putMapping returns always null


I have a PutMapping that would first check the Reward-Entity and then if exists, it would further proceed to update the 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);
}

This is now challenging for me when i attempt to write a Test-case for this, in the below format

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


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

I always get NullPointerException when the below line in test-code gets executed

rewardResponse.getBody().getReward();

because always the below-condition in the actual code becomes true and it is always returning HttpStatus.NOT_FOUND

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

How to tackle this ?


Solution

  • I tackled this by calling exactly what the Controller in original code is doing.. First, i called Optional --> getRewardIdFromDatabase() code stuff through my test code i executed the update method of the Controller