|
| 1 | +package com.connect.service; |
| 2 | + |
| 3 | +import com.connect.dto.LoginUserDTO; |
| 4 | +import com.connect.enums.UserStatus; |
| 5 | +import com.connect.exception.DuplicateResourceException; |
| 6 | +import com.connect.exception.TimeoutException; |
| 7 | +import com.connect.exception.UserCreationException; |
| 8 | +import com.connect.model.User; |
| 9 | +import com.connect.repository.UserRepository; |
| 10 | +import com.connect.security.CustomUserDetails; |
| 11 | +import com.connect.utils.EmailUtil; |
| 12 | +import com.connect.utils.JwtUtil; |
| 13 | +import org.junit.jupiter.api.Assertions; |
| 14 | +import org.junit.jupiter.api.Test; |
| 15 | +import org.junit.jupiter.api.extension.ExtendWith; |
| 16 | +import org.mockito.InjectMocks; |
| 17 | +import org.mockito.Mock; |
| 18 | +import org.mockito.Mockito; |
| 19 | +import org.mockito.junit.jupiter.MockitoExtension; |
| 20 | +import org.springframework.security.authentication.AuthenticationManager; |
| 21 | +import org.springframework.security.authentication.BadCredentialsException; |
| 22 | +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; |
| 23 | +import org.springframework.security.core.Authentication; |
| 24 | + |
| 25 | +import java.util.Date; |
| 26 | +import java.util.Map; |
| 27 | +import java.util.Optional; |
| 28 | +import java.util.concurrent.CompletableFuture; |
| 29 | + |
| 30 | +@ExtendWith(MockitoExtension.class) |
| 31 | +public class AuthServiceTest { |
| 32 | + |
| 33 | + @InjectMocks |
| 34 | + private AuthService authService; |
| 35 | + |
| 36 | + @Mock |
| 37 | + private UserRepository userRepository; |
| 38 | + |
| 39 | + @Mock |
| 40 | + private OTPService otpService; |
| 41 | + |
| 42 | + @Mock |
| 43 | + private EmailService emailService; |
| 44 | + |
| 45 | + @Mock |
| 46 | + private RedisService redisService; |
| 47 | + |
| 48 | + @Mock |
| 49 | + private EmailUtil emailUtil; |
| 50 | + |
| 51 | + @Mock |
| 52 | + private JwtUtil jwtUtil; |
| 53 | + |
| 54 | + @Mock |
| 55 | + private AuthenticationManager authenticationManager; |
| 56 | + |
| 57 | + @Test |
| 58 | + public void testSignupHandler_WhenNewUser_ThenOpenSentAndCached() { |
| 59 | + User newUser = User.builder() |
| 60 | + .username("aditya") |
| 61 | + .email("adi@gmail.com") |
| 62 | + .password("aditya123") |
| 63 | + .build(); |
| 64 | + |
| 65 | + // Mocking the repository |
| 66 | + Mockito.when(userRepository.findByEmail(newUser.getEmail())).thenReturn(Optional.empty()); |
| 67 | + Mockito.when(userRepository.findByUsername(newUser.getUsername())).thenReturn(Optional.empty()); |
| 68 | + |
| 69 | + // Mocking OTP generation |
| 70 | + Mockito.when(otpService.generateOTPForUser(newUser.getEmail())).thenReturn("1234"); |
| 71 | + |
| 72 | + // Mocking the email body |
| 73 | + Mockito.when(emailUtil.getBody()).thenReturn("Hello %s, This is OTP, %s"); |
| 74 | + |
| 75 | + // Doing nothing for side effects |
| 76 | + Mockito.doNothing().when(emailService).sendEmail(newUser.getEmail(), "One Time Password", "Hello aditya, This is OTP, 1234"); |
| 77 | + |
| 78 | + Mockito.doNothing().when(redisService).cacheUserWithTTL(newUser); |
| 79 | + |
| 80 | + // Main act |
| 81 | + authService.signupHandler(newUser); |
| 82 | + |
| 83 | + // Verifying the behavior that the function run or not. |
| 84 | + Mockito.verify(userRepository).findByEmail(newUser.getEmail()); |
| 85 | + Mockito.verify(userRepository).findByUsername(newUser.getUsername()); |
| 86 | + Mockito.verify(otpService).generateOTPForUser(newUser.getEmail()); |
| 87 | + Mockito.verify(emailUtil).getBody(); |
| 88 | + Mockito.verify(emailService).sendEmail(newUser.getEmail(), "One Time Password", "Hello aditya, This is OTP, 1234"); |
| 89 | + Mockito.verify(redisService).cacheUserWithTTL(newUser); |
| 90 | + } |
| 91 | + |
| 92 | + @Test |
| 93 | + public void testSignupHandler_withExistedEmail() { |
| 94 | + User user = User.builder() |
| 95 | + .username("aditya") |
| 96 | + .email("adi@gmail.com") |
| 97 | + .password("aditya123") |
| 98 | + .build(); |
| 99 | + |
| 100 | + // Mocking the repository. |
| 101 | + Mockito.when(userRepository.findByEmail(user.getEmail())).thenReturn(Optional.of(user)); |
| 102 | + |
| 103 | + // So as per the behavior of the method if the user found it will throws up a DuplicateResourceException. |
| 104 | + // act |
| 105 | + Assertions.assertThrows(DuplicateResourceException.class, () -> { |
| 106 | + authService.signupHandler(user); |
| 107 | + }); |
| 108 | + } |
| 109 | + |
| 110 | + @Test |
| 111 | + public void testSignupHandler_withExistedUsername() { |
| 112 | + User user = User.builder() |
| 113 | + .username("aditya") |
| 114 | + .email("adi@gmail.com") |
| 115 | + .password("aditya123") |
| 116 | + .build(); |
| 117 | + |
| 118 | + // Note: Still you are testing for the username you have to mock the email too. |
| 119 | + // Cause this is the flow of the method otherwise it will lead to failure situations. |
| 120 | + // When we didn't mock the email in that case mockito will return null so it didn't throw the exception. |
| 121 | + |
| 122 | + // Mocking email |
| 123 | + Mockito.when(userRepository.findByEmail(user.getEmail())).thenReturn(Optional.empty()); |
| 124 | + |
| 125 | + Mockito.when(userRepository.findByUsername(user.getUsername())).thenReturn(Optional.of(user)); |
| 126 | + |
| 127 | + // act |
| 128 | + Assertions.assertThrows(DuplicateResourceException.class, () -> { |
| 129 | + authService.signupHandler(user); |
| 130 | + }); |
| 131 | + } |
| 132 | + |
| 133 | + @Test |
| 134 | + public void testResendOTP_WhenValidEmail_ThenOTPRemovedFromCache() { |
| 135 | + |
| 136 | + String email = "adi@gmail.com"; |
| 137 | + |
| 138 | + // Mocking Redis Service |
| 139 | + Mockito.when(redisService.getUser(email)) |
| 140 | + .thenReturn(User.builder() |
| 141 | + .username("aditya") |
| 142 | + .email(email). |
| 143 | + password("aditya123") |
| 144 | + .build()); |
| 145 | + |
| 146 | + // Do nothing for side effects |
| 147 | + Mockito.when(redisService.removeOTP(email)).thenReturn(true); |
| 148 | + |
| 149 | + // Mocking the OTP |
| 150 | + Mockito.when(otpService.generateOTPForUser(email)).thenReturn("1234"); |
| 151 | + |
| 152 | + // Mocking the email util |
| 153 | + Mockito.when(emailUtil.getBody()).thenReturn("Hey %s, This is OTP, %s"); |
| 154 | + |
| 155 | + // Mocking the email service |
| 156 | + Mockito.doNothing().when(emailService).sendEmail(email, "One Time Password", "Hey aditya, This is OTP, 1234"); |
| 157 | + |
| 158 | + // Main act |
| 159 | + authService.resendOTP(email); |
| 160 | + |
| 161 | + // Verifying mocks |
| 162 | + Mockito.verify(redisService).getUser(email); |
| 163 | + Mockito.verify(redisService).removeOTP(email); |
| 164 | + Mockito.verify(otpService).generateOTPForUser(email); |
| 165 | + Mockito.verify(emailUtil).getBody(); |
| 166 | + Mockito.verify(emailService).sendEmail(email, "One Time Password", "Hey aditya, This is OTP, 1234"); |
| 167 | + } |
| 168 | + |
| 169 | + @Test |
| 170 | + public void testResendOTP_withInvalidEmail() { |
| 171 | + String email = "adi@gmail.com"; |
| 172 | + |
| 173 | + Mockito.when(redisService.getUser(email)).thenReturn(null); |
| 174 | + |
| 175 | + // Act |
| 176 | + RuntimeException exception = Assertions.assertThrows(RuntimeException.class, () -> { |
| 177 | + authService.resendOTP(email); |
| 178 | + }); |
| 179 | + |
| 180 | + Assertions.assertEquals("Email doesn't exists, Bad Request!", exception.getMessage()); |
| 181 | + } |
| 182 | + |
| 183 | + @Test |
| 184 | + public void testCreateUser_withValidOTP() { |
| 185 | + String email = "adi@gmail.com"; |
| 186 | + String otp = "1234"; |
| 187 | + |
| 188 | + User user = User.builder() |
| 189 | + .username("aditya") |
| 190 | + .email(email) |
| 191 | + .password("aditya123").build(); |
| 192 | + |
| 193 | + Mockito.when(otpService.verifyOTP(email, otp)).thenReturn(true); |
| 194 | + |
| 195 | + // Mocking the remove otp function. |
| 196 | + Mockito.when(redisService.removeOTP(email)).thenReturn(true); |
| 197 | + |
| 198 | + // Mocking the getUser() function. |
| 199 | + Mockito.when(redisService.getUser(email)).thenReturn(user); |
| 200 | + |
| 201 | + Mockito.when(userRepository.createUser(user)).thenReturn(Optional.of(user)); |
| 202 | + |
| 203 | + Mockito.when(redisService.removeUser(email)).thenReturn(true); |
| 204 | + |
| 205 | + // Act |
| 206 | + Assertions.assertNotNull(authService.createUser(otp, email)); |
| 207 | + |
| 208 | + // Verifying the mocks |
| 209 | + Mockito.verify(otpService).verifyOTP(email, otp); |
| 210 | + Mockito.verify(redisService).removeOTP(email); |
| 211 | + Mockito.verify(redisService).getUser(email); |
| 212 | + Mockito.verify(userRepository).createUser(user); |
| 213 | + Mockito.verify(redisService).removeUser(email); |
| 214 | + } |
| 215 | + |
| 216 | + @Test |
| 217 | + public void testCreateUser_withInvalidOTP() { |
| 218 | + |
| 219 | + Mockito.when(otpService.verifyOTP("adi@gmail.com", "1234")).thenReturn(false); |
| 220 | + |
| 221 | + RuntimeException exception = Assertions.assertThrows(RuntimeException.class, () -> { |
| 222 | + authService.createUser("1234", "adi@gmail.com"); |
| 223 | + }); |
| 224 | + |
| 225 | + Assertions.assertEquals("Invalid OTP", exception.getMessage()); |
| 226 | + } |
| 227 | + |
| 228 | + @Test |
| 229 | + public void testCreateUser_withValidOTP_ThenUserNotFoundInCache() { |
| 230 | + String email = "adi@gmail.com"; |
| 231 | + String otp = "1234"; |
| 232 | + |
| 233 | + Mockito.when(otpService.verifyOTP(email, otp)).thenReturn(true); |
| 234 | + |
| 235 | + // Mocking the remove otp function. |
| 236 | + Mockito.when(redisService.removeOTP(email)).thenReturn(true); |
| 237 | + |
| 238 | + Mockito.when(redisService.getUser(email)).thenReturn(null); |
| 239 | + |
| 240 | + TimeoutException exception = Assertions.assertThrows(TimeoutException.class, () -> { |
| 241 | + authService.createUser(otp, email); |
| 242 | + }); |
| 243 | + |
| 244 | + Assertions.assertEquals("User not found in the cache, Try again later", exception.getMessage()); |
| 245 | + } |
| 246 | + |
| 247 | + @Test |
| 248 | + public void testCreateUser_withValidOTP_ThenFailedToSaveUser() { |
| 249 | + String email = "adi@gmail.com"; |
| 250 | + String otp = "1234"; |
| 251 | + |
| 252 | + User user = User.builder() |
| 253 | + .username("aditya") |
| 254 | + .email(email) |
| 255 | + .password("aditya123").build(); |
| 256 | + |
| 257 | + Mockito.when(otpService.verifyOTP(email, otp)).thenReturn(true); |
| 258 | + |
| 259 | + // Mocking the remove otp function. |
| 260 | + Mockito.when(redisService.removeOTP(email)).thenReturn(true); |
| 261 | + |
| 262 | + // Mocking the getUser() function. |
| 263 | + Mockito.when(redisService.getUser(email)).thenReturn(user); |
| 264 | + |
| 265 | + Mockito.when(userRepository.createUser(user)).thenReturn(Optional.empty()); |
| 266 | + |
| 267 | + UserCreationException exception = Assertions.assertThrows(UserCreationException.class, () -> { |
| 268 | + authService.createUser(otp, email); |
| 269 | + }); |
| 270 | + |
| 271 | + Assertions.assertEquals("Something went wrong at the server! try again later.", exception.getMessage()); |
| 272 | + } |
| 273 | + |
| 274 | + @Test |
| 275 | + public void testLoginHandler_WhenCredentialsValid_ThenReturnTokenAndExpiry() throws Exception { |
| 276 | + User user = User.builder() |
| 277 | + .username("aditya") |
| 278 | + .email("adi@gmail.com") |
| 279 | + .password("aditya123") |
| 280 | + .build(); |
| 281 | + String token = "auth-token"; |
| 282 | + Date expiryDate = new Date(System.currentTimeMillis() + 1000 * 60 * 60); |
| 283 | + |
| 284 | + // Mocking user details |
| 285 | + CustomUserDetails customUserDetails = new CustomUserDetails(user); |
| 286 | + |
| 287 | + // Mocking authentication |
| 288 | + Authentication authentication = Mockito.mock(Authentication.class); |
| 289 | + Mockito.when(authentication.getPrincipal()).thenReturn(customUserDetails); |
| 290 | + |
| 291 | + Mockito.when(authenticationManager.authenticate( |
| 292 | + new UsernamePasswordAuthenticationToken(user.getEmail(), user.getPassword()) |
| 293 | + )).thenReturn(authentication); |
| 294 | + |
| 295 | + // Mocking JWT Utility classes |
| 296 | + Mockito.when(jwtUtil.generateToken(user.getUsername(), user.getEmail())).thenReturn(token); |
| 297 | + Mockito.when(jwtUtil.getExpirationDate(token)).thenReturn(expiryDate); |
| 298 | + |
| 299 | + Mockito.when(userRepository.updateUserStatus(user.getUsername(), UserStatus.ACTIVE)).thenReturn(CompletableFuture.completedFuture(Optional.of(user))); |
| 300 | + |
| 301 | + // Act |
| 302 | + Map<String, Object> result = authService.loginHandler( |
| 303 | + LoginUserDTO.builder() |
| 304 | + .email(user.getEmail()) |
| 305 | + .password(user.getPassword()).build()); |
| 306 | + |
| 307 | + Assertions.assertEquals(token, result.get("token")); |
| 308 | + Assertions.assertEquals(expiryDate, result.get("expiresAt")); |
| 309 | + |
| 310 | + // Verify |
| 311 | + |
| 312 | + Mockito.verify(authenticationManager).authenticate(Mockito.any(UsernamePasswordAuthenticationToken.class)); |
| 313 | + Mockito.verify(jwtUtil).generateToken(user.getUsername(), user.getEmail()); |
| 314 | + Mockito.verify(jwtUtil).getExpirationDate(token); |
| 315 | + Mockito.verify(userRepository).updateUserStatus(user.getUsername(), UserStatus.ACTIVE); |
| 316 | + } |
| 317 | + |
| 318 | + @Test |
| 319 | + public void testLoginHandler_WhenCredentialsInvalid_ThenThrowException() { |
| 320 | + LoginUserDTO user = LoginUserDTO.builder() |
| 321 | + .email("wrongemail@gmail.com") |
| 322 | + .password("wrongpass") |
| 323 | + .build(); |
| 324 | + Mockito.when(authenticationManager.authenticate(Mockito.any())) |
| 325 | + .thenThrow(new BadCredentialsException("Bad Credentials")); |
| 326 | + |
| 327 | + Exception exception = Assertions.assertThrows(BadCredentialsException.class, () -> { |
| 328 | + authService.loginHandler(user); |
| 329 | + }); |
| 330 | + |
| 331 | + Assertions.assertEquals("Bad Credentials", exception.getMessage()); |
| 332 | + } |
| 333 | + |
| 334 | +} |
0 commit comments