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);
}