-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuthenticationServiceTest.java
More file actions
293 lines (246 loc) · 12.6 KB
/
AuthenticationServiceTest.java
File metadata and controls
293 lines (246 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
package com.podzilla.auth.service;
import com.podzilla.auth.dto.CustomGrantedAuthority;
import com.podzilla.auth.dto.LoginRequest;
import com.podzilla.auth.dto.SignupRequest;
import com.podzilla.auth.exception.ValidationException;
import com.podzilla.auth.model.Address;
import com.podzilla.auth.model.ERole;
import com.podzilla.auth.model.Role;
import com.podzilla.auth.model.User;
import com.podzilla.auth.repository.RoleRepository;
import com.podzilla.auth.repository.UserRepository;
import com.podzilla.mq.EventPublisher;
import com.podzilla.mq.EventsConstants;
import com.podzilla.mq.events.BaseEvent;
import com.podzilla.mq.events.CustomerRegisteredEvent;
import com.podzilla.auth.dto.DeliveryAddress;
import jakarta.servlet.http.HttpServletRequest; // Added import
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import java.util.Collections;
import java.util.Optional;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class AuthenticationServiceTest {
@Mock
private AuthenticationManager authenticationManager;
@Mock
private PasswordEncoder passwordEncoder;
@Mock
private UserRepository userRepository;
@Mock
private TokenService tokenService;
@Mock
private RoleRepository roleRepository;
@Mock
private HttpServletResponse httpServletResponse;
@Mock // Added mock for HttpServletRequest
private HttpServletRequest httpServletRequest;
@Mock
private EventPublisher eventPublisher;
@InjectMocks
private AuthenticationService authenticationService;
private SignupRequest signupRequest;
private LoginRequest loginRequest;
private User user;
private Role userRole;
@BeforeEach
void setUp() {
signupRequest = new SignupRequest();
signupRequest.setName("Test User");
signupRequest.setEmail("test@example.com");
signupRequest.setPassword("password123");
signupRequest.setMobileNumber("1234567890");
DeliveryAddress deliveryAddress = new DeliveryAddress();
deliveryAddress.setStreet("123 Test St");
deliveryAddress.setCity("Test City");
deliveryAddress.setState("Test State");
deliveryAddress.setCountry("Test Country");
deliveryAddress.setPostalCode("12345");
signupRequest.setAddress(deliveryAddress);
loginRequest = new LoginRequest();
loginRequest.setEmail("test@example.com");
loginRequest.setPassword("password123");
userRole = new Role(ERole.ROLE_USER);
user = User.builder()
.id(UUID.randomUUID())
.name("Test User")
.email("test@example.com")
.password("encodedPassword")
.roles(Collections.singleton(userRole))
.build();
SecurityContextHolder.getContext().setAuthentication(null);
}
// --- registerAccount Tests ---
@Test
void registerAccount_shouldSaveUser_whenEmailNotExistsAndPasswordNotEmpty() {
// Arrange
when(userRepository.existsByEmail(signupRequest.getEmail())).thenReturn(false);
when(passwordEncoder.encode(signupRequest.getPassword())).thenReturn("encodedPassword");
when(roleRepository.findByErole(ERole.ROLE_USER)).thenReturn(Optional.of(userRole));
when(userRepository.save(any(User.class))).thenReturn(user); // Return the saved user
// mock publish event in event publisher void method
doNothing().when(eventPublisher).publishEvent(any(EventsConstants.EventMetadata.class),
any(CustomerRegisteredEvent.class));
// Act
authenticationService.registerAccount(signupRequest);
// Assert
verify(userRepository).existsByEmail(signupRequest.getEmail());
verify(passwordEncoder).encode(signupRequest.getPassword());
verify(roleRepository).findByErole(ERole.ROLE_USER);
// Capture the user argument passed to save
ArgumentCaptor<User> userCaptor = ArgumentCaptor.forClass(User.class);
verify(userRepository).save(userCaptor.capture());
User savedUser = userCaptor.getValue();
assertEquals(signupRequest.getName(), savedUser.getName());
assertEquals(signupRequest.getEmail(), savedUser.getEmail());
assertEquals("encodedPassword", savedUser.getPassword());
assertTrue(savedUser.getRoles().contains(userRole));
}
@Test
void registerAccount_shouldThrowValidationException_whenEmailExists() {
// Arrange
when(userRepository.existsByEmail(signupRequest.getEmail())).thenReturn(true);
// Act & Assert
ValidationException exception = assertThrows(ValidationException.class, () -> {
authenticationService.registerAccount(signupRequest);
});
assertEquals("Validation error: Email already in use.",
exception.getMessage());
verify(userRepository).existsByEmail(signupRequest.getEmail());
verify(passwordEncoder, never()).encode(anyString());
verify(roleRepository, never()).findByErole(any());
verify(userRepository, never()).save(any(User.class));
}
@Test
void registerAccount_shouldHandleRoleNotFoundGracefully() {
// Arrange - Simulate role not found in DB
when(userRepository.existsByEmail(signupRequest.getEmail())).thenReturn(false);
when(passwordEncoder.encode(signupRequest.getPassword())).thenReturn("encodedPassword");
when(roleRepository.findByErole(ERole.ROLE_USER)).thenReturn(Optional.empty()); // Role not found
// Act
ValidationException exception = assertThrows(ValidationException.class, () -> {
authenticationService.registerAccount(signupRequest);
});
assertEquals("Validation error: Role_USER not found.",
exception.getMessage());
// Assert
verify(userRepository).existsByEmail(signupRequest.getEmail());
verify(passwordEncoder).encode(signupRequest.getPassword());
verify(roleRepository).findByErole(ERole.ROLE_USER);
}
// --- login Tests ---
@Test
void login_shouldReturnUsernameAndSetTokens_whenCredentialsAreValid() {
// Arrange
UserDetails userDetails = new org.springframework.security.core.userdetails.User(
loginRequest.getEmail(),
"encodedPassword", // Password doesn't matter much here as AuthenticationManager handles it
Collections.singletonList(new CustomGrantedAuthority("ROLE_USER"))
);
Authentication successfulAuth = new UsernamePasswordAuthenticationToken(
userDetails, // Principal
loginRequest.getPassword(), // Credentials
userDetails.getAuthorities() // Authorities
);
// Mock AuthenticationManager behavior
when(authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class)))
.thenReturn(successfulAuth);
// Mocks for token generation (void methods, no 'when' needed unless checking args)
// doNothing().when(tokenService).generateAccessToken(anyString(), any(HttpServletResponse.class));
// doNothing().when(tokenService).generateRefreshToken(anyString(), any(HttpServletResponse.class));
// Act
String loggedInUsername = authenticationService.login(loginRequest, httpServletResponse);
// Assert
assertEquals(loginRequest.getEmail(), loggedInUsername);
// Verify AuthenticationManager was called with unauthenticated token
ArgumentCaptor<UsernamePasswordAuthenticationToken> authCaptor =
ArgumentCaptor.forClass(UsernamePasswordAuthenticationToken.class);
verify(authenticationManager).authenticate(authCaptor.capture());
UsernamePasswordAuthenticationToken capturedAuthRequest = authCaptor.getValue();
assertEquals(loginRequest.getEmail(), capturedAuthRequest.getName());
assertEquals(loginRequest.getPassword(), capturedAuthRequest.getCredentials());
assertFalse(capturedAuthRequest.isAuthenticated()); // Ensure it was unauthenticated initially
// Verify token generation methods were called
verify(tokenService).generateAccessToken(loginRequest.getEmail(), httpServletResponse);
verify(tokenService).generateRefreshToken(loginRequest.getEmail(), httpServletResponse);
}
@Test
void login_shouldThrowException_whenCredentialsAreInvalid() {
// Arrange
// Mock AuthenticationManager to throw an exception for bad credentials
when(authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class)))
.thenThrow(new BadCredentialsException("Invalid credentials"));
// Act & Assert
assertThrows(BadCredentialsException.class, () -> {
authenticationService.login(loginRequest, httpServletResponse);
});
// Verify token generation methods were NOT called
verify(tokenService, never()).generateAccessToken(anyString(), any(HttpServletResponse.class));
verify(tokenService, never()).generateRefreshToken(anyString(), any(HttpServletResponse.class));
}
// --- logoutUser Tests ---
@Test
void logoutUser_shouldCallTokenServiceToRemoveTokens() {
// Arrange (no specific arrangement needed as methods are void)
// Act
authenticationService.logoutUser(httpServletResponse);
// Assert
verify(tokenService).removeAccessTokenFromCookie(httpServletResponse);
verify(tokenService).removeRefreshTokenFromCookieAndExpire(httpServletResponse);
}
// --- refreshToken Tests ---
@Test
void refreshToken_shouldReturnEmailAndGenerateAccessToken_whenTokenIsValid() {
// Arrange
String expectedEmail = "test@example.com";
String validRefreshToken = "valid-refresh-token";
when(tokenService.getRefreshTokenFromCookie(httpServletRequest)).thenReturn(validRefreshToken);
when(tokenService.renewRefreshToken(validRefreshToken, httpServletResponse)).thenReturn(expectedEmail);
// No need to mock generateAccessToken as it's void, we just verify it
// Act
String actualEmail = authenticationService.refreshToken(httpServletRequest, httpServletResponse);
// Assert
assertEquals(expectedEmail, actualEmail);
verify(tokenService).getRefreshTokenFromCookie(httpServletRequest);
verify(tokenService).renewRefreshToken(validRefreshToken, httpServletResponse);
verify(tokenService).generateAccessToken(expectedEmail, httpServletResponse);
}
@Test
void refreshToken_shouldThrowAccessDeniedException_whenTokenIsInvalid() {
// Arrange
String invalidRefreshToken = "invalid-refresh-token";
when(tokenService.getRefreshTokenFromCookie(httpServletRequest)).thenReturn(invalidRefreshToken);
// Mock renewRefreshToken to throw the exception caught in the service method
when(tokenService.renewRefreshToken(invalidRefreshToken, httpServletResponse))
.thenThrow(new IllegalArgumentException("Token invalid"));
// Act & Assert
AccessDeniedException exception = assertThrows(AccessDeniedException.class, () -> {
authenticationService.refreshToken(httpServletRequest, httpServletResponse);
});
assertEquals("Invalid refresh token.",
exception.getMessage());
verify(tokenService).getRefreshTokenFromCookie(httpServletRequest);
verify(tokenService).renewRefreshToken(invalidRefreshToken, httpServletResponse);
// Verify generateAccessToken was NOT called in the failure case
verify(tokenService, never()).generateAccessToken(anyString(), any(HttpServletResponse.class));
}
}