Search code examples
javaspringspring-bootmockitojunit5

spring boot unit test for service layer method return null pointer exception


I have created a unit test for my service layer method and when i called this method i have an nullpointer exception

In my test class

@Test
  void whencreateOrUpdateUser() {

    final var userDto = new UserDto();
    userDto.setId(UUID.randomUUID());
    userDto.setName("toto");

    final var userEntity = mock(UserEntity.class);

    when(userRepository.findByUserIdAndType(UUID.randomUUID(), UserTypes.ACTIF))
        .thenReturn(Optional.of(userEntity));
    when(userRepository.save(userEntity)).thenReturn(userEntity);
    when(userMapper.toDto(userEntity)).thenReturn(userDto);

    // When

    final var result = service.createOrUpdateUser(userDto);

    // Then

    assertEquals(result, userDto);
  }

In my service class, i have this method

public UserDto createOrUpdateUser(UserDto userDto) {

    var newUser =
        userRepository
            .findByUserIdAndType(userDto.getUserId(), UserType.ACTIF)
            .map(
                existingUser -> {
                  var updatedUserDto = userMapper.toEntity(userDto);
                  updatedUserDto.setId(existingUser.getId());

                  return userRepository.save(updatedUserDto);
                })
            .orElseGet(() -> userRepository.save(userMapper.toEntity(userDto)));

    return UserMapper.toDto(newUser);
  }

When i call this service layer method in my test i have a null pointer exception :

java.lang.NullPointerException: Cannot invoke "com.project.univ.model.updatedUserDto .setId(java.lang.Long)" because "updatedUserDto" is null

how can i fix this please


Solution

  • Its clear on your provided error message.

    java.lang.NullPointerException: Cannot invoke
    "com.project.univ.model.updatedUserDto.setId(java.lang.Long)"
    because "updatedUserDto" is null
    

    On your code, updatedUserDto property has this method call:

    UpdatedUserDto.setId(existingUserId);
    

    if updatedUserDto is a inject property, please mock and stub it.

     @Mock
     private InjectBean bean;
    
     // Stub
     doReturn(entity).when(bean).methodCall(any());
    

    Or, use this to star a integration test.

    @SpringBootTest(classes = YourStarterClass.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)