\$\begingroup\$
\$\endgroup\$
3
Service class:
package personal.progresscompaninon.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import personal.progresscompaninon.dto.PasswordChangeDto;
import personal.progresscompaninon.exception.*;
import personal.progresscompaninon.model.Role;
import personal.progresscompaninon.model.User;
import personal.progresscompaninon.repository.RoleRepository;
import personal.progresscompaninon.repository.UserRepository;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Collection;
@Service
public class UserService implements UserDetailsService {
@Autowired
private final UserRepository userRepository;
@Autowired
private RoleRepository roleRepository;
BCryptPasswordEncoder bCryptPasswordEncoder;
public UserService(UserRepository userRepository, RoleRepository roleRepository) {
this.userRepository = userRepository;
this.roleRepository = roleRepository;
bCryptPasswordEncoder = new BCryptPasswordEncoder();
}
public void addUser(@Valid User user) {
if (findByEmail(user.getEmail()) != null) {
throw new UserAlreadyRegisteredException("User already registered");
}
user.getRoles().add(roleRepository.findByRole("ROLE_USER"));
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
userRepository.save(user);
}
public void changePassword(@Valid PasswordChangeDto passwords) {
User user = getLoggedInUser();
if (bCryptPasswordEncoder.matches(passwords.getOldPassword(), user.getPassword())) {
if (passwordValidator(passwords.getNewPassword())) {
userRepository.changePassword(bCryptPasswordEncoder.encode(passwords.getNewPassword()), user.getEmail());
System.out.println(user.getPassword());
}
} else {
throw new WrongPasswordException("Old password didn't match");
}
}
public User findByEmail(String email) {
return userRepository.findByEmail(email);
}
public boolean passwordValidator(String password) {
return password.length() > 8;
}
public User getLoggedInUser() {
return userRepository.findByEmail(SecurityContextHolder.getContext().getAuthentication().getName());
}
public User getUser(long id) {
return userRepository.findById(id).get();
}
public void deleteUser(long id) {
userRepository.deleteById(id);
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByEmail(username);
if (user == null) {
throw new UsernameNotFoundException("User not found in the database");
}
Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
for (Role role : user.getRoles()) {
authorities.add(new SimpleGrantedAuthority(role.getName()));
}
return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), authorities);
}
Tests:
@ExtendWith(MockitoExtension.class)
@ExtendWith(SpringExtension.class)
class UserServiceTest {
@Mock
private UserRepository userRepositoryMock;
@Mock
private RoleRepository roleRepositoryMock;
private UserService userService;
@BeforeEach
public void setup() {
userService = new UserService(userRepositoryMock, roleRepositoryMock);
}
@Test
void shouldAddUser() {
String role = "ROLE_USER";
User user = new User(0L, "test", "test", "[email protected]", "yesyesyes", new ArrayList<>(), null);
Mockito.when(roleRepositoryMock.findByRole(role)).thenReturn(new Role(1L, role, null));
userService.addUser(user);
Mockito.verify(roleRepositoryMock).findByRole(role);
Mockito.verify(userRepositoryMock).save(user);
}
@Test
void shouldThrowAlreadyRegisteredException() {
UserService userService = new UserService(userRepositoryMock, roleRepositoryMock);
String email = "[email protected]";
User user = new User(0L, "test", "test", email, "yesyesyes", new ArrayList<>(), null);
Mockito.when(userRepositoryMock.findByEmail(email)).thenReturn(user);
Exception exception = assertThrows(UserAlreadyRegisteredException.class, () -> userService.addUser(user));
Assert.assertEquals("User already registered", exception.getMessage());
}
@Test
void invalidPasswordTest() {
UserService userService = new UserService(null, null);
String password = "qwert";
assertFalse(userService.passwordValidator(password));
}
}
Been learning Spring boot recently and wrote a simple CRUD api, I have never done any kind of testing before and this is my first attempt writing tests for service layer
-
1\$\begingroup\$ Could you please edit so that the title describes the purpose of the code under test? We really need to understand the motivational context to give good reviews - knowing that these are your first tests doesn't help with that. Thanks! \$\endgroup\$Toby Speight– Toby Speight2022年02月22日 10:49:43 +00:00Commented Feb 22, 2022 at 10:49
-
\$\begingroup\$ You're starting to learn unit testing? Well, I wish I had seen this before I started doing unit tests... youtube.com/watch?v=EZ05e7EMOLM \$\endgroup\$TorbenPutkonen– TorbenPutkonen2022年02月22日 14:28:35 +00:00Commented Feb 22, 2022 at 14:28
-
1\$\begingroup\$ The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see How do I ask a good question?. \$\endgroup\$BCdotWEB– BCdotWEB2022年02月23日 11:04:31 +00:00Commented Feb 23, 2022 at 11:04
1 Answer 1
\$\begingroup\$
\$\endgroup\$
The test looks good. except that you do not have to initialize the UserService
again inside the Test like below, since @BeforeEach
is being called every time before each test
@Test
void shouldThrowAlreadyRegisteredException() {
UserService userService = new UserService(userRepositoryMock, roleRepositoryMock);
}
answered Feb 23, 2022 at 10:49
lang-java