Repository navigation
Expand file tree
/
Copy pathUserServiceTest.java
More file actions
409 lines (343 loc) · 17.9 KB
/
Copy pathUserServiceTest.java
File metadata and controls
409 lines (343 loc) · 17.9 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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
package com.wallet.secure.user.service;
import com.wallet.secure.audit.service.AuditService;
import com.wallet.secure.auth.service.SessionService;
import com.wallet.secure.common.exception.EmailAlreadyExistsException;
import com.wallet.secure.common.exception.InvalidCredentialsException;
import com.wallet.secure.common.exception.UnauthorizedOperationException;
import com.wallet.secure.common.exception.UserNotFoundException;
import com.wallet.secure.common.response.ApiResponse;
import com.wallet.secure.common.enums.UserRole;
import com.wallet.secure.user.dto.RegisterRequest;
import com.wallet.secure.user.dto.UpdateProfileRequest;
import com.wallet.secure.user.dto.UserResponse;
import com.wallet.secure.user.entity.User;
import com.wallet.secure.user.repository.UserRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.security.crypto.password.PasswordEncoder;
import java.util.Optional;
import java.util.UUID;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
/**
* Unit tests for UserService.
*
* WHY unit tests (not integration):
* - No Spring context → runs in milliseconds
* - No DB → completely isolated
* - Mocks replace real dependencies → test only the business logic
*
* @ExtendWith(MockitoExtension.class) → enables Mockito in JUnit 5
* @Mock → creates a fake object (no real DB or BCrypt calls)
* @InjectMocks → creates UserService injecting the mocks above
*/
@ExtendWith(MockitoExtension.class)
@DisplayName("UserService Unit Tests")
class UserServiceTest {
@Mock
private UserRepository userRepository;
@Mock
private PasswordEncoder passwordEncoder;
@Mock
private AuditService auditService;
@Mock
private SessionService sessionService;
@InjectMocks
private UserService userService;
// ─── Shared test data ─────────────────────────────────────────────────────
private User testUser;
private UUID testUserId;
@BeforeEach
void setUp() {
testUserId = UUID.randomUUID();
testUser = User.builder()
.email("pedro@test.com")
.passwordHash("$2a$12$hashedPassword")
.role(UserRole.USER)
.build();
// Simulate DB-generated ID
testUser.setId(testUserId);
}
// ─── register() ───────────────────────────────────────────────────────────
@Nested
@DisplayName("register()")
class RegisterTests {
/**
* Happy path — email available, password gets hashed, user saved.
* Verifies: BCrypt is called, entity is saved, response has correct data.
*/
@Test
@DisplayName("Should register user successfully when email is available")
void shouldRegisterUserSuccessfully() {
// ARRANGE — prepare inputs and mock behavior
RegisterRequest request = new RegisterRequest();
setField(request, "email", "pedro@test.com");
setField(request, "password", "SecurePass12!");
when(userRepository.existsByEmail("pedro@test.com")).thenReturn(false);
when(passwordEncoder.encode("SecurePass12!")).thenReturn("$2a$12$hashed");
when(userRepository.save(any(User.class))).thenReturn(testUser);
// ACT — call the method under test
ApiResponse<UserResponse> response = userService.register(request);
// ASSERT — verify the result
assertThat(response.isSuccess()).isTrue();
assertThat(response.getMessage()).isEqualTo("User registered successfully");
assertThat(response.getData().getEmail()).isEqualTo("pedro@test.com");
assertThat(response.getData().getRole()).isEqualTo(UserRole.USER);
// Verify BCrypt was called — password must be hashed
verify(passwordEncoder).encode("SecurePass12!");
// Verify user was saved to DB
ArgumentCaptor<User> savedUser = ArgumentCaptor.forClass(User.class);
verify(userRepository).save(savedUser.capture());
// OWASP A01: RegisterRequest has no role field and service fixes USER.
assertThat(savedUser.getValue().getRole()).isEqualTo(UserRole.USER);
}
/**
* Email already taken → EmailAlreadyExistsException.
* OWASP A07: message should not reveal if email exists.
*/
@Test
@DisplayName("Should throw EmailAlreadyExistsException when email is taken")
void shouldThrowWhenEmailAlreadyExists() {
// ARRANGE
RegisterRequest request = new RegisterRequest();
setField(request, "email", "existing@test.com");
setField(request, "password", "SecurePass12!");
when(userRepository.existsByEmail("existing@test.com")).thenReturn(true);
// ACT & ASSERT — expect the exception
assertThatThrownBy(() -> userService.register(request))
.isInstanceOf(EmailAlreadyExistsException.class)
.hasMessage("Email already in use");
// Verify BCrypt was NEVER called — fail fast before hashing
verify(passwordEncoder, never()).encode(anyString());
// Verify save was NEVER called
verify(userRepository, never()).save(any());
}
}
// ─── getProfile() ─────────────────────────────────────────────────────────
@Nested
@DisplayName("getProfile()")
class GetProfileTests {
@Test
@DisplayName("Should return profile when user exists")
void shouldReturnProfileWhenUserExists() {
// ARRANGE
when(userRepository.findById(testUserId)).thenReturn(Optional.of(testUser));
// ACT
ApiResponse<UserResponse> response = userService.getProfile(testUserId);
// ASSERT
assertThat(response.isSuccess()).isTrue();
assertThat(response.getData().getEmail()).isEqualTo("pedro@test.com");
// OWASP A02: sensitive fields must NOT be in UserResponse
// UserResponse doesn't have passwordHash — compile-time check
}
@Test
@DisplayName("Should throw UserNotFoundException when user does not exist")
void shouldThrowWhenUserNotFound() {
// ARRANGE
UUID nonExistentId = UUID.randomUUID();
when(userRepository.findById(nonExistentId)).thenReturn(Optional.empty());
// ACT & ASSERT
assertThatThrownBy(() -> userService.getProfile(nonExistentId))
.isInstanceOf(UserNotFoundException.class)
.hasMessage("User not found");
}
@Test
@DisplayName("Should return profile even when account is deactivated")
void shouldReturnProfileOfDeactivatedAccount() {
// ARRANGE — usuario con isActive = false
User deactivatedUser = User.builder()
.email("inactive@test.com")
.passwordHash("$2a$12$hash")
.role(UserRole.USER)
.build();
deactivatedUser.setId(testUserId);
deactivatedUser.setIsActive(false); // ← cuenta desactivada
when(userRepository.findById(testUserId))
.thenReturn(Optional.of(deactivatedUser));
// ACT
ApiResponse<UserResponse> response = userService.getProfile(testUserId);
// ASSERT
// UserService devuelve el perfil — el Controller decide si mostrarlo
assertThat(response.isSuccess()).isTrue();
assertThat(response.getData().getIsActive()).isFalse(); // ← visible en respuesta
}
@Test
@DisplayName("Should return deactivated status in UserResponse")
void shouldExposeDeactivatedStatusInResponse() {
// ARRANGE
testUser.setIsActive(false);
when(userRepository.findById(testUserId)).thenReturn(Optional.of(testUser));
// ACT
ApiResponse<UserResponse> response = userService.getProfile(testUserId);
// ASSERT — isActive=false se refleja en el DTO (no se oculta)
assertThat(response.getData().getIsActive()).isFalse();
}
}
// ─── updateProfile() ──────────────────────────────────────────────────────
@Nested
@DisplayName("updateProfile()")
class UpdateProfileTests {
@Test
@DisplayName("Should update password successfully with correct current password")
void shouldUpdatePasswordSuccessfully() {
// ARRANGE
UpdateProfileRequest request = new UpdateProfileRequest();
setField(request, "currentPassword", "OldPass12!");
setField(request, "password", "NewPass12!");
when(userRepository.findById(testUserId)).thenReturn(Optional.of(testUser));
when(passwordEncoder.matches("OldPass12!", "$2a$12$hashedPassword"))
.thenReturn(true);
when(passwordEncoder.matches("NewPass12!", "$2a$12$hashedPassword"))
.thenReturn(false);
when(passwordEncoder.encode("NewPass12!")).thenReturn("$2a$12$newHash");
when(userRepository.save(any(User.class))).thenReturn(testUser);
// ACT
ApiResponse<UserResponse> response = userService.updateProfile(testUserId, request);
// ASSERT
assertThat(response.isSuccess()).isTrue();
verify(passwordEncoder).encode("NewPass12!");
verify(userRepository).save(any(User.class));
// OWASP A09: password change MUST generate an audit log entry
verify(auditService).logPasswordChange(eq(testUserId), anyString(), isNull(), isNull());
}
@Test
@DisplayName("Should throw InvalidCredentialsException when current password is wrong")
void shouldThrowWhenCurrentPasswordIsWrong() {
// ARRANGE
UpdateProfileRequest request = new UpdateProfileRequest();
setField(request, "currentPassword", "WrongPass12!");
setField(request, "password", "NewPass12!");
when(userRepository.findById(testUserId)).thenReturn(Optional.of(testUser));
when(passwordEncoder.matches("WrongPass12!", "$2a$12$hashedPassword"))
.thenReturn(false);
// ACT & ASSERT
assertThatThrownBy(() -> userService.updateProfile(testUserId, request))
.isInstanceOf(InvalidCredentialsException.class)
.hasMessage("Current password is incorrect");
// New password must NEVER be encoded if current is wrong
verify(passwordEncoder, never()).encode(anyString());
}
@Test
@DisplayName("Should throw when new password is same as current")
void shouldThrowWhenNewPasswordSameAsCurrent() {
// ARRANGE
UpdateProfileRequest request = new UpdateProfileRequest();
setField(request, "currentPassword", "SamePass12!");
setField(request, "password", "SamePass12!");
when(userRepository.findById(testUserId)).thenReturn(Optional.of(testUser));
when(passwordEncoder.matches("SamePass12!", "$2a$12$hashedPassword"))
.thenReturn(true) // current password OK
.thenReturn(true); // new == current
// ACT & ASSERT
assertThatThrownBy(() -> userService.updateProfile(testUserId, request))
.isInstanceOf(InvalidCredentialsException.class)
.hasMessage("New password must be different from current password");
}
}
// ─── deactivateAccount() ──────────────────────────────────────────────────
@Nested
@DisplayName("deactivateAccount()")
class DeactivateTests {
@Test
@DisplayName("Should reject a regular user attempting to deactivate their own account")
void shouldRejectSelfServiceDeactivationByRegularUser() {
// GIVEN — no self-service endpoint exists, and the service enforces
// the same bank-style rule for any future internal caller.
when(userRepository.findById(testUserId)).thenReturn(Optional.of(testUser));
// WHEN / THEN
assertThatThrownBy(() -> userService.deactivateAccount(testUserId, testUserId))
.isInstanceOf(UnauthorizedOperationException.class)
.hasMessage("Not authorized to deactivate this account");
verify(userRepository, never()).save(any());
verify(sessionService, never()).revokeAllSessions(any());
verify(auditService, never()).logUserDeactivation(any(), any());
}
@Test
@DisplayName("Should allow ADMIN to deactivate another user")
void shouldAllowAdminToDeactivateAnotherUser() {
// GIVEN — admin (different UUID) deactivates target user
UUID adminId = UUID.randomUUID();
User adminUser = User.builder()
.email("admin@test.com")
.passwordHash("$2a$12$adminHash")
.role(UserRole.ADMIN)
.build();
adminUser.setId(adminId);
// findById is called twice: once for the target, once for the requester
when(userRepository.findById(testUserId)).thenReturn(Optional.of(testUser));
when(userRepository.findById(adminId)).thenReturn(Optional.of(adminUser));
when(userRepository.save(any(User.class))).thenReturn(testUser);
// WHEN
ApiResponse<Void> response = userService.deactivateAccount(testUserId, adminId);
// THEN
assertThat(response.isSuccess()).isTrue();
verify(userRepository).save(argThat(u -> !u.getIsActive()));
verify(sessionService).revokeAllSessions(testUserId);
verify(auditService).logUserDeactivation(adminId, testUserId);
}
@Test
@DisplayName("Should throw UnauthorizedOperationException when non-ADMIN tries to deactivate another user")
void shouldThrowWhenNonAdminTriesToDeactivateAnotherUser() {
// GIVEN — a regular USER tries to deactivate someone else's account
UUID intruderId = UUID.randomUUID();
User intruder = User.builder()
.email("intruder@test.com")
.passwordHash("$2a$12$hash")
.role(UserRole.USER)
.build();
intruder.setId(intruderId);
when(userRepository.findById(testUserId)).thenReturn(Optional.of(testUser));
when(userRepository.findById(intruderId)).thenReturn(Optional.of(intruder));
// WHEN / THEN
assertThatThrownBy(() -> userService.deactivateAccount(testUserId, intruderId))
.isInstanceOf(UnauthorizedOperationException.class);
// Account must NOT have been deactivated
verify(userRepository, never()).save(any());
verify(auditService, never()).logUserDeactivation(any(), any());
}
@Test
@DisplayName("Should reject an ADMIN trying to deactivate another ADMIN")
void shouldRejectAdminDeactivationOfAnotherAdmin() {
// GIVEN
UUID requesterId = UUID.randomUUID();
User targetAdmin = User.builder().email("target-admin@test.com")
.passwordHash("$2a$12$targetAdminHash").role(UserRole.ADMIN).build();
targetAdmin.setId(testUserId);
User requesterAdmin = User.builder().email("requester-admin@test.com")
.passwordHash("$2a$12$requesterAdminHash").role(UserRole.ADMIN).build();
requesterAdmin.setId(requesterId);
when(userRepository.findById(testUserId)).thenReturn(Optional.of(targetAdmin));
when(userRepository.findById(requesterId)).thenReturn(Optional.of(requesterAdmin));
// WHEN / THEN
assertThatThrownBy(() -> userService.deactivateAccount(testUserId, requesterId))
.isInstanceOf(UnauthorizedOperationException.class)
.hasMessage("Not authorized to deactivate this account");
verify(userRepository, never()).save(any());
verify(sessionService, never()).revokeAllSessions(any());
verify(auditService, never()).logUserDeactivation(any(), any());
}
}
// ─── Test helper ──────────────────────────────────────────────────────────
/**
* Sets a private field via reflection — needed because DTOs use
* private fields with no setters (Lombok @Getter only).
* Only used in tests — never in production code.
*/
private void setField(Object target, String fieldName, Object value) {
try {
var field = target.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
field.set(target, value);
} catch (Exception e) {
throw new RuntimeException("Failed to set field: " + fieldName, e);
}
}
}