0

I have a service method in my Java Spring server that's supposed to save the user to the DB.

@Override
public User addUser(User user) {
    log.info("Saving new user {} to the database", user.getUsername());
    user.setPassword(passwordEncoder.encode(user.getPassword()));
    return userRepository.save(user);

}

And then I have the test class.

@Slf4j
@ExtendWith(MockitoExtension.class)
public class UserTest {
@InjectMocks
UserServiceImpl userService;

@Mock
private UserRepository userRepository;
@Mock
private PasswordEncoder passwordEncoder;

@ParameterizedTest
@CsvSource({
        "username, password, 1, test@test.com, admin, true",
})
void checkIfUserCanBeAdded(String username,String password,int group_id,String email,String role,Boolean active){
    
    //given
    User user = new User(username, password, group_id, email, role, active);

    //when
    User result = userService.addUser(user);

    //then
    assertSame(result.getUsername(),user.getUsername());
    assertSame(result.getPassword(), user.getPassword());
    assertSame(result.getGroup_id(), user.getGroup_id());
    assertSame(result.getEmail(), user.getEmail());
    assertSame(result.getEmail(), user.getEmail());
    }
}

But apparently the userRepository.save() method returns null

java.lang.NullPointerException: Cannot invoke "sensor.management.sensor_admin.domain.entity.User.getUsername()" because "result" is null

What's the solution to it? Why it doesn't work?

Edit: I decided to changed the test to the code bellow,and it works as it is right now

    @BeforeEach
    public void setup(){
        user = new User(1,"username", "password", 1, "test@test.com", "admin", true);
    }

    @Test
    void checkIfUserCanBeAdded(){

        //given
        given(userRepository.save(user)).willReturn(user);

        //when
        User savedUser = userService.addUser(user);

        assertNotNull(savedUser);
    }
m3k_1
  • 383
  • 4
  • 15
  • 2
    you are creating a mock of the userRepository so you neeed to tell your test what to return after hiting userRepository.save() – Anon Dec 13 '22 at 18:20
  • 1
    you didn't mock method calls - https://stackoverflow.com/a/39436666/4778343 – Stefan Golubović Dec 13 '22 at 18:21
  • Is there any other way to inject the dependencies while creating UserServiceImpl instance? And if we are talking about mock and what you said, how to tell the test what to return – m3k_1 Dec 13 '22 at 18:22
  • Stefan Golubović linked you the page on what to do – Anon Dec 13 '22 at 18:24

1 Answers1

0

Please add below statements before User result = userService.addUser(user); and try again.

Mockito.when(passwordEncoder.encode(Mockito.anyString())).thenReturn(user.getPassword());
Mockito.when(userRepository.save(Mockito.any())).thenReturn(user);
Rohit Agarwal
  • 763
  • 2
  • 5
  • 10