|
| 1 | +package org.baeldung.userservice; |
| 2 | + |
| 3 | +import org.baeldung.custom.config.MvcConfig; |
| 4 | +import org.baeldung.custom.config.PersistenceDerbyJPAConfig; |
| 5 | +import org.baeldung.custom.config.SecSecurityConfig; |
| 6 | +import org.baeldung.user.service.MyUserService; |
| 7 | +import org.baeldung.web.MyUserDto; |
| 8 | +import org.junit.Test; |
| 9 | +import org.junit.runner.RunWith; |
| 10 | +import org.springframework.beans.factory.annotation.Autowired; |
| 11 | +import org.springframework.boot.test.SpringApplicationConfiguration; |
| 12 | +import org.springframework.security.authentication.AuthenticationProvider; |
| 13 | +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; |
| 14 | +import org.springframework.security.core.Authentication; |
| 15 | +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; |
| 16 | +import org.springframework.test.context.web.WebAppConfiguration; |
| 17 | +import static org.junit.Assert.*; |
| 18 | + |
| 19 | +import java.util.logging.Level; |
| 20 | +import java.util.logging.Logger; |
| 21 | + |
| 22 | +@RunWith(SpringJUnit4ClassRunner.class) |
| 23 | +@SpringApplicationConfiguration(classes = { MvcConfig.class, PersistenceDerbyJPAConfig.class, SecSecurityConfig.class }) |
| 24 | +@WebAppConfiguration |
| 25 | +public class CustomUserDetailsServiceTest { |
| 26 | + |
| 27 | + private static final Logger LOG = Logger.getLogger("CustomUserDetailsServiceTest"); |
| 28 | + |
| 29 | + public static final String USERNAME = "user"; |
| 30 | + public static final String PASSWORD = "pass"; |
| 31 | + |
| 32 | + @Autowired |
| 33 | + MyUserService myUserService; |
| 34 | + |
| 35 | + @Autowired |
| 36 | + AuthenticationProvider authenticationProvider; |
| 37 | + |
| 38 | + @Test |
| 39 | + public void whenAuthenticateUser_thenRetrieveFromDb() { |
| 40 | + try { |
| 41 | + MyUserDto userDTO = new MyUserDto(); |
| 42 | + userDTO.setUsername(USERNAME); |
| 43 | + userDTO.setPassword(PASSWORD); |
| 44 | + |
| 45 | + myUserService.registerNewUserAccount(userDTO); |
| 46 | + |
| 47 | + UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME, PASSWORD); |
| 48 | + Authentication authentication = authenticationProvider.authenticate(auth); |
| 49 | + |
| 50 | + assertEquals(authentication.getName(), USERNAME); |
| 51 | + |
| 52 | + } catch (Exception exc) { |
| 53 | + LOG.log(Level.SEVERE, "Error creating account"); |
| 54 | + } finally { |
| 55 | + myUserService.removeUserByUsername(USERNAME); |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | +} |
0 commit comments