-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathUserTest.java
More file actions
283 lines (228 loc) · 9.99 KB
/
UserTest.java
File metadata and controls
283 lines (228 loc) · 9.99 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
package contactapp.security;
import contactapp.domain.Validation;
import java.time.Instant;
import java.util.UUID;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.NullAndEmptySource;
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.security.core.GrantedAuthority;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/**
* Tests the User entity validation.
*
* <p>Verifies:
* <ul>
* <li>Successful creation with valid data</li>
* <li>Invalid inputs cause IllegalArgumentException with specific messages</li>
* <li>UserDetails interface implementation</li>
* <li>Boundary conditions for field lengths</li>
* </ul>
*/
class UserTest {
private static final String VALID_USERNAME = "testuser";
private static final String VALID_EMAIL = "test@example.com";
/** Valid BCrypt hash format: $2a$10$ prefix + 53 chars = 60 total. Fake hash for testing only. */
private static final String VALID_PASSWORD = "$2a$10$TESTHASHaaaaaaaaaaaaaaBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB";
private static final String MIN_VALID_EMAIL = "a@b.co";
private static final String EMAIL_DOMAIN = "@example.com";
// ==================== Successful Creation Tests ====================
@Test
void testSuccessfulCreation() {
User user = new User(VALID_USERNAME, VALID_EMAIL, VALID_PASSWORD, Role.USER);
assertThat(user.getUsername()).isEqualTo(VALID_USERNAME);
assertThat(user.getEmail()).isEqualTo(VALID_EMAIL);
assertThat(user.getPassword()).isEqualTo(VALID_PASSWORD);
assertThat(user.getRole()).isEqualTo(Role.USER);
assertThat(user.isEnabled()).isTrue();
}
@Test
void testCreationWithAdminRole() {
User user = new User(VALID_USERNAME, VALID_EMAIL, VALID_PASSWORD, Role.ADMIN);
assertThat(user.getRole()).isEqualTo(Role.ADMIN);
}
@Test
void testConstructorTrimsUsernameAndEmail() {
User user = new User(" testuser ", " test@example.com ", VALID_PASSWORD, Role.USER);
assertThat(user.getUsername()).isEqualTo("testuser");
assertThat(user.getEmail()).isEqualTo("test@example.com");
}
// ==================== UserDetails Interface Tests ====================
@Test
void testGetAuthoritiesReturnsRoleWithPrefix() {
User user = new User(VALID_USERNAME, VALID_EMAIL, VALID_PASSWORD, Role.USER);
assertThat(user.getAuthorities())
.hasSize(1)
.extracting(GrantedAuthority::getAuthority)
.containsExactly("ROLE_USER");
}
@Test
void testGetAuthoritiesForAdmin() {
User user = new User(VALID_USERNAME, VALID_EMAIL, VALID_PASSWORD, Role.ADMIN);
assertThat(user.getAuthorities())
.extracting(GrantedAuthority::getAuthority)
.containsExactly("ROLE_ADMIN");
}
@Test
void testAccountStatusMethodsReturnTrue() {
User user = new User(VALID_USERNAME, VALID_EMAIL, VALID_PASSWORD, Role.USER);
assertThat(user.isAccountNonExpired()).isTrue();
assertThat(user.isAccountNonLocked()).isTrue();
assertThat(user.isCredentialsNonExpired()).isTrue();
assertThat(user.isEnabled()).isTrue();
}
/**
* Ensures {@link User#isEnabled()} returns the actual field value rather
* than a hardcoded constant. PIT flagged a surviving mutant where
* returning {@code true} unconditionally went undetected.
*/
@Test
void testIsEnabledReturnsFalseWhenDisabled() {
User user = new User(VALID_USERNAME, VALID_EMAIL, VALID_PASSWORD, Role.USER);
user.setEnabled(false);
assertThat(user.isEnabled()).isFalse();
}
// ==================== Username Validation Tests ====================
@ParameterizedTest
@NullAndEmptySource
@ValueSource(strings = {" ", "\t", "\n"})
void testUsernameBlankThrows(String username) {
assertThatThrownBy(() -> new User(username, VALID_EMAIL, VALID_PASSWORD, Role.USER))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Username");
}
@Test
void testUsernameAtMaxLength() {
String maxUsername = "a".repeat(Validation.MAX_USERNAME_LENGTH);
User user = new User(maxUsername, VALID_EMAIL, VALID_PASSWORD, Role.USER);
assertThat(user.getUsername()).hasSize(Validation.MAX_USERNAME_LENGTH);
}
@Test
void testUsernameOverMaxLengthThrows() {
String tooLong = "a".repeat(Validation.MAX_USERNAME_LENGTH + 1);
assertThatThrownBy(() -> new User(tooLong, VALID_EMAIL, VALID_PASSWORD, Role.USER))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Username")
.hasMessageContaining("length");
}
// ==================== Email Validation Tests ====================
@ParameterizedTest
@NullAndEmptySource
@ValueSource(strings = {" ", "\t", "\n"})
void testEmailBlankThrows(String email) {
assertThatThrownBy(() -> new User(VALID_USERNAME, email, VALID_PASSWORD, Role.USER))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Email");
}
@Test
void testEmailAtMaxLength() {
String maxEmail = emailOfLength(Validation.MAX_EMAIL_LENGTH);
User user = new User(VALID_USERNAME, maxEmail, VALID_PASSWORD, Role.USER);
assertThat(user.getEmail()).hasSize(Validation.MAX_EMAIL_LENGTH);
}
@Test
void testEmailOverMaxLengthThrows() {
String tooLong = emailOfLength(Validation.MAX_EMAIL_LENGTH + 1);
assertThatThrownBy(() -> new User(VALID_USERNAME, tooLong, VALID_PASSWORD, Role.USER))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Email")
.hasMessageContaining("length");
}
@Test
void testEmailMinimalValidLength() {
User user = new User(VALID_USERNAME, MIN_VALID_EMAIL, VALID_PASSWORD, Role.USER);
assertThat(user.getEmail()).isEqualTo(MIN_VALID_EMAIL);
}
@ParameterizedTest
@ValueSource(strings = {
"plainaddress",
"missing-at.example.com",
"user@",
"user@domain",
"user@domain.",
"user@domain..com"
})
void testEmailInvalidFormatThrows(String email) {
assertThatThrownBy(() -> new User(VALID_USERNAME, email, VALID_PASSWORD, Role.USER))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Email")
.hasMessageContaining("valid email");
}
// ==================== Password Validation Tests ====================
@ParameterizedTest
@NullAndEmptySource
@ValueSource(strings = {" ", "\t", "\n"})
void testPasswordBlankThrows(String password) {
assertThatThrownBy(() -> new User(VALID_USERNAME, VALID_EMAIL, password, Role.USER))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Password");
}
@Test
void testPasswordAcceptsBcryptHash() {
// BCrypt hashes are always exactly 60 characters
User user = new User(VALID_USERNAME, VALID_EMAIL, VALID_PASSWORD, Role.USER);
assertThat(user.getPassword()).hasSize(60);
}
@Test
void testPasswordOverMaxLengthThrows() {
String tooLong = "a".repeat(Validation.MAX_PASSWORD_LENGTH + 1);
assertThatThrownBy(() -> new User(VALID_USERNAME, VALID_EMAIL, tooLong, Role.USER))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Password")
.hasMessageContaining("length");
}
@Test
void testPasswordMustBeBcryptHash() {
assertThatThrownBy(() -> new User(VALID_USERNAME, VALID_EMAIL, "plain-text", Role.USER))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("BCrypt hash");
}
@Test
void testIdGetterReturnsAssignedValue() {
User user = new User(VALID_USERNAME, VALID_EMAIL, VALID_PASSWORD, Role.USER);
UUID testId = UUID.randomUUID();
user.setId(testId);
assertThat(user.getId()).isEqualTo(testId);
}
@Test
void testTimestampLifecycleCallbacksPopulateValues() {
User user = new User(VALID_USERNAME, VALID_EMAIL, VALID_PASSWORD, Role.USER);
user.onCreate();
Instant created = user.getCreatedAt();
Instant firstUpdated = user.getUpdatedAt();
assertThat(created).isNotNull();
assertThat(firstUpdated).isEqualTo(created);
user.onUpdate();
Instant secondUpdated = user.getUpdatedAt();
assertThat(secondUpdated).isNotNull();
assertThat(secondUpdated).isAfterOrEqualTo(created);
}
// ==================== Role Validation Tests ====================
@Test
void testNullRoleThrows() {
assertThatThrownBy(() -> new User(VALID_USERNAME, VALID_EMAIL, VALID_PASSWORD, null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Role");
}
// ==================== Boundary Tests ====================
@ParameterizedTest
@CsvSource({
"1, valid single char username",
"50, valid max length username"
})
void testUsernameBoundaryLengths(int length, String description) {
assertThat(description).isNotBlank();
String username = "a".repeat(length);
User user = new User(username, VALID_EMAIL, VALID_PASSWORD, Role.USER);
assertThat(user.getUsername()).hasSize(length);
}
private static String emailOfLength(int length) {
if (length <= EMAIL_DOMAIN.length()) {
throw new IllegalArgumentException("Length must be greater than domain size");
}
int localPartLength = length - EMAIL_DOMAIN.length();
return "a".repeat(localPartLength) + EMAIL_DOMAIN;
}
}