Skip to content

Commit f8a6191

Browse files
committed
features: improve defeat for unit testing
1 parent 7a9a5e2 commit f8a6191

File tree

2 files changed

+96
-24
lines changed

2 files changed

+96
-24
lines changed

src/main/java/com/app/login/security/DomainUserDetailsServiceImpl.java

+23-10
Original file line numberDiff line numberDiff line change
@@ -29,22 +29,35 @@ public DomainUserDetailsServiceImpl(UserRepository userRepository) {
2929
this.userRepository = userRepository;
3030
}
3131

32+
/**
33+
* Loads the user details by the given username.
34+
* This method is used by Spring Security to authenticate a user.
35+
*
36+
* @param login The username of the user to be authenticated.
37+
* @return The UserDetails object representing the authenticated user.
38+
* @throws UsernameNotFoundException If the user with the given username is not found in the database.
39+
* @throws UserNotActivatedException If the user is found but is not activated.
40+
*/
3241
@Override
3342
@Transactional(rollbackFor = Exception.class)
3443
public UserDetails loadUserByUsername(final String login) {
44+
if (login==null){
45+
throw new UsernameNotFoundException("User login is null");
46+
}
3547
log.debug("Authenticating {}", login);
3648
String lowercaseLogin = login.toLowerCase(Locale.ENGLISH);
3749
Optional<User> userFromDatabase = userRepository.findOneWithAuthoritiesByLogin(lowercaseLogin);
3850
return userFromDatabase.map(user -> {
39-
if (!user.isActivated()) {
40-
throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated");
41-
}
42-
List<GrantedAuthority> grantedAuthorities = user.getAuthorities()
43-
.stream()
44-
.map(authority -> new SimpleGrantedAuthority(authority.getName()))
45-
.collect(Collectors.toList());
46-
return new org.springframework.security.core.userdetails.User(lowercaseLogin, user.getPassword(), grantedAuthorities);
47-
})
48-
.orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the " + "database"));
51+
if (!user.isActivated()) {
52+
throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated");
53+
}
54+
List<GrantedAuthority> grantedAuthorities = user.getAuthorities()
55+
.stream()
56+
.map(authority -> new SimpleGrantedAuthority(authority.getName()))
57+
.collect(Collectors.toList());
58+
return new org.springframework.security.core.userdetails.User(lowercaseLogin, user.getPassword(), grantedAuthorities);
59+
})
60+
.orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the " + "database"));
4961
}
62+
5063
}

src/test/java/com/app/login/service/DomainUserDetailsServiceImplAIGenTest.java

+73-14
Original file line numberDiff line numberDiff line change
@@ -51,16 +51,14 @@ public void setUp() {
5151

5252
@Test
5353
public void testLoadUserByUsername_Success() {
54-
// Mock the repository to return the test user
54+
// Arrange
5555
when(userRepository.findOneWithAuthoritiesByLogin(anyString())).thenReturn(Optional.of(testUser));
5656

57-
// Call the method under test
57+
// Act
5858
UserDetails userDetails = userDetailsService.loadUserByUsername("testuser");
5959

60-
// Verify the interactions with the mock
60+
// Assert
6161
verify(userRepository, times(1)).findOneWithAuthoritiesByLogin("testuser");
62-
63-
// Assert the returned user details
6462
assertNotNull(userDetails);
6563
assertEquals("testuser", userDetails.getUsername());
6664
assertEquals("encodedPassword", userDetails.getPassword());
@@ -74,33 +72,94 @@ public void testLoadUserByUsername_Success() {
7472

7573
@Test
7674
public void testLoadUserByUsername_UserNotActivated() {
77-
// Create a test user that is not activated
75+
// Arrange
7876
User inactiveUser = new User();
7977
inactiveUser.setId(1L);
8078
inactiveUser.setLogin("inactiveuser");
8179
inactiveUser.setPassword("encodedPassword");
8280
inactiveUser.setActivated(false);
8381
inactiveUser.setEmail("[email protected]");
8482

85-
// Mock the repository to return the inactive user
8683
when(userRepository.findOneWithAuthoritiesByLogin(anyString())).thenReturn(Optional.of(inactiveUser));
8784

88-
// Call the method under test and expect an exception
85+
// Act & Assert
8986
assertThrows(UserNotActivatedException.class, () -> userDetailsService.loadUserByUsername("inactiveuser"));
90-
91-
// Verify the interactions with the mock
9287
verify(userRepository, times(1)).findOneWithAuthoritiesByLogin("inactiveuser");
9388
}
9489

9590
@Test
9691
public void testLoadUserByUsername_UserNotFound() {
97-
// Mock the repository to return an empty optional
92+
// Arrange
9893
when(userRepository.findOneWithAuthoritiesByLogin(anyString())).thenReturn(Optional.empty());
9994

100-
// Call the method under test and expect an exception
95+
// Act & Assert
10196
assertThrows(UsernameNotFoundException.class, () -> userDetailsService.loadUserByUsername("nonexistentuser"));
102-
103-
// Verify the interactions with the mock
10497
verify(userRepository, times(1)).findOneWithAuthoritiesByLogin("nonexistentuser");
10598
}
99+
100+
@Test
101+
public void testLoadUserByUsername_EmptyLogin() {
102+
// Arrange
103+
when(userRepository.findOneWithAuthoritiesByLogin(anyString())).thenReturn(Optional.empty());
104+
105+
// Act & Assert
106+
assertThrows(UsernameNotFoundException.class, () -> userDetailsService.loadUserByUsername(""));
107+
verify(userRepository, times(1)).findOneWithAuthoritiesByLogin("");
108+
}
109+
110+
@Test
111+
public void testLoadUserByUsername_NullLogin() {
112+
113+
// Act & Assert
114+
assertThrows(UsernameNotFoundException.class, () -> userDetailsService.loadUserByUsername(null));
115+
}
116+
117+
@Test
118+
public void testLoadUserByUsername_NoAuthorities() {
119+
// Arrange
120+
User userWithoutAuthorities = new User();
121+
userWithoutAuthorities.setId(1L);
122+
userWithoutAuthorities.setLogin("userwithoutauthorities");
123+
userWithoutAuthorities.setPassword("encodedPassword");
124+
userWithoutAuthorities.setActivated(true);
125+
userWithoutAuthorities.setEmail("[email protected]");
126+
userWithoutAuthorities.setAuthorities(Collections.emptySet());
127+
128+
when(userRepository.findOneWithAuthoritiesByLogin(anyString())).thenReturn(Optional.of(userWithoutAuthorities));
129+
130+
// Act
131+
UserDetails userDetails = userDetailsService.loadUserByUsername("userwithoutauthorities");
132+
133+
// Assert
134+
verify(userRepository, times(1)).findOneWithAuthoritiesByLogin("userwithoutauthorities");
135+
assertNotNull(userDetails);
136+
assertEquals("userwithoutauthorities", userDetails.getUsername());
137+
assertEquals("encodedPassword", userDetails.getPassword());
138+
assertTrue(userDetails.isAccountNonExpired());
139+
assertTrue(userDetails.isAccountNonLocked());
140+
assertTrue(userDetails.isCredentialsNonExpired());
141+
assertTrue(userDetails.isEnabled());
142+
assertTrue(userDetails.getAuthorities().isEmpty());
143+
}
144+
145+
@Test
146+
public void testLoadUserByUsername_CaseInsensitiveLogin() {
147+
// Arrange
148+
when(userRepository.findOneWithAuthoritiesByLogin(anyString())).thenReturn(Optional.of(testUser));
149+
150+
// Act
151+
UserDetails userDetails = userDetailsService.loadUserByUsername("TESTUSER");
152+
153+
// Assert
154+
verify(userRepository, times(1)).findOneWithAuthoritiesByLogin("testuser");
155+
assertNotNull(userDetails);
156+
assertEquals("testuser", userDetails.getUsername());
157+
assertEquals("encodedPassword", userDetails.getPassword());
158+
assertTrue(userDetails.isAccountNonExpired());
159+
assertTrue(userDetails.isAccountNonLocked());
160+
assertTrue(userDetails.isCredentialsNonExpired());
161+
assertTrue(userDetails.isEnabled());
162+
assertEquals(1, userDetails.getAuthorities().size());
163+
assertTrue(userDetails.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_USER")));
164+
}
106165
}

0 commit comments

Comments
 (0)