UserServiceTest JUnit
This commit is contained in:
parent
0c3a5143d7
commit
4e675ce615
BIN
.DS_Store
vendored
BIN
.DS_Store
vendored
Binary file not shown.
@ -1,5 +1,7 @@
|
||||
package com.pvt.smiletServer;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
|
||||
@ -10,5 +12,7 @@ public interface UserRepository extends CrudRepository<User, Integer> {
|
||||
|
||||
public Iterable<User> findAll(Sort by);
|
||||
|
||||
public Optional<User> existsByUsername(String username);
|
||||
|
||||
|
||||
}
|
||||
|
@ -1,3 +1,16 @@
|
||||
/*
|
||||
* Hantera användarrelaterade operationer:
|
||||
* UserService innehåller metoder för att utföra operationer som att lägga till en användare,
|
||||
* autentisera en användare, och validera användaruppgifter.
|
||||
Validering av affärsregler:
|
||||
Tjänstklassen säkerställer att alla affärsregler följs, t.ex. att användarnamn och lösenord uppfyller vissa krav.
|
||||
Samverkan med UserRepository:
|
||||
UserService interagerar med databasen via UserRepository för att hämta, spara, och kontrollera
|
||||
existensen av användare.
|
||||
Felfallshantering: Tjänstklassen kan kasta undantag vid olika fel, vilket gör det enklare att
|
||||
hantera fel i applikationen på ett centraliserat sätt.
|
||||
*/
|
||||
|
||||
package com.pvt.smiletServer;
|
||||
|
||||
|
||||
@ -8,68 +21,48 @@ import org.springframework.stereotype.Service;
|
||||
public class UserService {
|
||||
|
||||
//For data retrieval to and from the database
|
||||
private final UserRepository userRepository;
|
||||
final UserRepository userRepository;
|
||||
|
||||
public UserService(UserRepository userRepository) {
|
||||
this.userRepository = userRepository;
|
||||
}
|
||||
|
||||
//Metoden fungerar inte riktigt som förväntat
|
||||
public boolean addUser(User user) {
|
||||
if (isValidUsername(user.getUsername()) && !userRepository.existsById(user.getId())) {
|
||||
userRepository.save(user);
|
||||
return true;
|
||||
public User registerUser(String userName, String password, int id) {
|
||||
if (userRepository.existsById(id)) {
|
||||
throw new IllegalArgumentException("Error: User with this ID already exists!");
|
||||
}
|
||||
return false;
|
||||
|
||||
if (isValidUserData(userName, password, id)) {
|
||||
User user = new User();
|
||||
user.setId(id);
|
||||
user.setUsername(userName);
|
||||
user.setPassword(password);
|
||||
user.setSchoolCode("someSchoolCode");
|
||||
|
||||
userRepository.save(user);
|
||||
return user;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/*public void addUser(String userName, String password, int id) {
|
||||
|
||||
|
||||
verifyUserData(userName, password, id);
|
||||
User user = new User();
|
||||
user.setUsername(userName);
|
||||
user.setPassword(password);
|
||||
user.setId(id);
|
||||
userRepository.save(user);
|
||||
|
||||
}*/
|
||||
|
||||
protected void verifyUserData(String userName, String password, int id) {
|
||||
protected boolean isValidUserData(String userName, String password, int id) {
|
||||
|
||||
if (!isValidUsername(userName)) {
|
||||
throw new IllegalArgumentException("Error: Invalid username");
|
||||
} else if (password == null || password.isEmpty()) {
|
||||
throw new IllegalArgumentException("Error: Password can't be empty");
|
||||
} else if (!isValidPassword(password)) {
|
||||
throw new IllegalArgumentException("Error: Invalid password format");
|
||||
} else if (userRepository.existsById(id)) {
|
||||
throw new IllegalArgumentException("Error: No such user!");
|
||||
throw new IllegalArgumentException("Error: Invalid password format");
|
||||
} else if (password == null || password.isEmpty()) {
|
||||
throw new IllegalArgumentException("Error: Password can't be empty");
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
//Retrieves user if present and user information is correct
|
||||
public User userLogin(String userName, String password, int id) {
|
||||
|
||||
Optional<User> optionalUser = userRepository.findById(id);
|
||||
|
||||
if (!optionalUser.isPresent()) {
|
||||
throw new IllegalArgumentException("Error: User does not exist!");
|
||||
}
|
||||
|
||||
User user = optionalUser.get();
|
||||
if (!user.getUsername().equals(userName) || !user.getPassword().equals(password)) {
|
||||
throw new IllegalArgumentException("Error: Invalid user credentials!");
|
||||
}
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
|
||||
//Help method for retrieving user by registration ID
|
||||
public Optional<User> getUserById(int id) {
|
||||
return userRepository.findById(id);
|
||||
}
|
||||
/* public void validateUserID (int id) {
|
||||
if (userRepository.existsById(id)) {
|
||||
throw new IllegalArgumentException("Error: User exists!");
|
||||
}
|
||||
} */
|
||||
|
||||
//Help method for validating username format
|
||||
public boolean isValidUsername(String username) {
|
||||
@ -78,11 +71,46 @@ public class UserService {
|
||||
|
||||
//Help method for validating password format
|
||||
public boolean isValidPassword(String password) {
|
||||
if (password == null) {
|
||||
if (password == null || password.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
String passwordPattern = "^(?=.*[A-Z])(?=.*[!@#$%^&*()-+]).{8,}$";
|
||||
return password.matches(passwordPattern);
|
||||
}
|
||||
|
||||
/* public boolean addUser(User user) {
|
||||
verifyUserData(user.getUsername(), user.getPassword(), user.getId());
|
||||
}
|
||||
|
||||
|
||||
|
||||
//Retrieves user if present and user information is correct
|
||||
public User userLogin(String userName, String password) {
|
||||
|
||||
Optional<User> optionalUser = getUserByUserName(userName);
|
||||
if (!optionalUser.isPresent()) {
|
||||
throw new IllegalArgumentException("User does not exist!");
|
||||
}
|
||||
User user = optionalUser.get();
|
||||
if (!user.getUsername().equals(userName) || !user.getPassword().equals(password)) {
|
||||
throw new IllegalArgumentException("Error: invalid credentials!");
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
//Help method for retrieving user by username
|
||||
public Optional<User> getUserByUserName(String username) {
|
||||
return userRepository.existsByUsername(username);
|
||||
}
|
||||
|
||||
//Help method for retrieving user by registration ID
|
||||
public Optional<User> getUserById(int id) {
|
||||
return userRepository.findById(id);
|
||||
}
|
||||
|
||||
|
||||
*/
|
||||
}
|
||||
|
@ -1,20 +1,18 @@
|
||||
package com.pvt.smiletServer;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.annotation.Rollback;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@SpringBootTest
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
|
||||
public class UserServiceTest {
|
||||
|
||||
@Mock
|
||||
@ -24,135 +22,54 @@ public class UserServiceTest {
|
||||
private UserService userService;
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
void setUp() {
|
||||
userService = new UserService(userRepository);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
@Rollback(true)
|
||||
public void testIsValidUsername() {
|
||||
assertTrue(userService.isValidUsername("validUser1"));
|
||||
assertTrue(userService.isValidUsername("short"));
|
||||
assertFalse(userService.isValidUsername("thisUsernameIsWayTooLong"));
|
||||
assertFalse(userService.isValidUsername("invalid user"));
|
||||
assertFalse(userService.isValidUsername(null));
|
||||
}
|
||||
void testRegisterUserWithExistingId() {
|
||||
int existingId = 1;
|
||||
String username = "validUser";
|
||||
String password = "Valid@123";
|
||||
|
||||
//Validates password format
|
||||
@Test
|
||||
@Transactional
|
||||
@Rollback(true)
|
||||
public void testIsValidPassword() {
|
||||
assertTrue(userService.isValidPassword("Password1!"));
|
||||
assertTrue(userService.isValidPassword("PASSWORD1!"));
|
||||
assertFalse(userService.isValidPassword("password1!"));
|
||||
assertFalse(userService.isValidPassword("Passw1!"));
|
||||
assertFalse(userService.isValidPassword("Password1"));
|
||||
assertFalse(userService.isValidPassword(null));
|
||||
}
|
||||
when(userRepository.existsById(existingId)).thenReturn(true);
|
||||
|
||||
|
||||
|
||||
@Test
|
||||
public void testAddUserInvalidUsername() {
|
||||
User user = new User();
|
||||
user.setId(1);
|
||||
user.setUsername("invalid user");
|
||||
user.setPassword("Password1!");
|
||||
user.setSchoolCode("1234");
|
||||
|
||||
userService.addUser(user);
|
||||
|
||||
boolean result = userService.addUser(user);
|
||||
assertFalse(result);
|
||||
verify(userRepository, never()).save(user);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
@Test
|
||||
public void testUserLoginUserNotExist() {
|
||||
when(userRepository.findById(1)).thenReturn(Optional.empty());
|
||||
|
||||
Exception exception = assertThrows(IllegalArgumentException.class, () -> {
|
||||
userService.userLogin("validUser1", "Password1!", 1);
|
||||
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {
|
||||
userService.registerUser(username, password, existingId);
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
|
||||
// Följande tester testAddUserExistingId() och testUserLoginSuccess() behöver fixas@Test
|
||||
|
||||
|
||||
/* @Transactional
|
||||
@Rollback(true)
|
||||
public void testAddUserInvalidPassword() {
|
||||
User user = new User();
|
||||
user.setId(1);
|
||||
user.setUsername("validUser1");
|
||||
user.setPassword("password"); // Saknar versal och specialtecken
|
||||
user.setSchoolCode("1234");
|
||||
|
||||
boolean result = userService.addUser(user);
|
||||
|
||||
assertFalse(result);
|
||||
verify(userRepository, never()).save(user);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Test
|
||||
public void testAddUserExistingId() {
|
||||
User user = new User();
|
||||
user.setId(1);
|
||||
user.setUsername("validUser1");
|
||||
user.setPassword("Password1!");
|
||||
user.setSchoolCode("1234");
|
||||
|
||||
when(userRepository.existsById(user.getId())).thenReturn(true);
|
||||
|
||||
boolean result = userService.addUser(user);
|
||||
|
||||
assertFalse(result);
|
||||
verify(userRepository, never()).save(user);
|
||||
assertEquals("Error: User with this ID already exists!", exception.getMessage());
|
||||
verify(userRepository, times(0)).save(any(User.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUserLoginSuccess() {
|
||||
User user = new User();
|
||||
user.setId(1);
|
||||
user.setUsername("validUser1");
|
||||
user.setPassword("Password1!");
|
||||
void testRegisterUserInvalidUsername() {
|
||||
int id = 100;
|
||||
when(userRepository.existsById(id)).thenReturn(false);
|
||||
|
||||
when(userRepository.findById(1)).thenReturn(Optional.of(user));
|
||||
|
||||
User result = userService.userLogin("validUser1", "Password1!", 1);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(user, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
@Rollback(true)
|
||||
public void testUserLoginInvalidCredentials() {
|
||||
User user = new User();
|
||||
user.setId(1);
|
||||
user.setUsername("validUser1");
|
||||
user.setPassword("Password1!");
|
||||
|
||||
when(userRepository.findById(1)).thenReturn(Optional.of(user));
|
||||
|
||||
Exception exception = assertThrows(IllegalArgumentException.class, () -> {
|
||||
userService.userLogin("validUser1", "WrongPassword!", 1);
|
||||
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {
|
||||
userService.registerUser("no", "Valid@123", id);
|
||||
});
|
||||
|
||||
assertEquals("Error: Invalid user credentials!", exception.getMessage());
|
||||
assertEquals("Error: Invalid username", exception.getMessage());
|
||||
verify(userRepository, times(0)).save(any(User.class));
|
||||
}
|
||||
|
||||
*/
|
||||
@Test
|
||||
void testRegisterUserInvalidPassword() {
|
||||
int id = 100;
|
||||
String username = "testuser97";
|
||||
String password = "invalid";
|
||||
|
||||
when(userRepository.existsById(id)).thenReturn(false);
|
||||
|
||||
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {
|
||||
userService.registerUser(username, password, id);
|
||||
});
|
||||
assertEquals("Error: Invalid password format", exception.getMessage());
|
||||
verify(userRepository, times(0)).save(any(User.class));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user