99import org .junit .runner .RunWith ;
1010import org .springframework .beans .factory .annotation .Autowired ;
1111import org .springframework .boot .test .SpringApplicationConfiguration ;
12+ import org .springframework .dao .DuplicateKeyException ;
1213import org .springframework .security .authentication .AuthenticationProvider ;
14+ import org .springframework .security .authentication .BadCredentialsException ;
1315import org .springframework .security .authentication .UsernamePasswordAuthenticationToken ;
1416import org .springframework .security .core .Authentication ;
17+ import org .springframework .security .core .userdetails .UsernameNotFoundException ;
1518import org .springframework .test .context .junit4 .SpringJUnit4ClassRunner ;
1619import org .springframework .test .context .web .WebAppConfiguration ;
1720import static org .junit .Assert .*;
@@ -28,6 +31,7 @@ public class CustomUserDetailsServiceTest {
2831
2932 public static final String USERNAME = "user" ;
3033 public static final String PASSWORD = "pass" ;
34+ public static final String USERNAME2 = "user2" ;
3135
3236 @ Autowired
3337 MyUserService myUserService ;
@@ -36,7 +40,7 @@ public class CustomUserDetailsServiceTest {
3640 AuthenticationProvider authenticationProvider ;
3741
3842 @ Test
39- public void whenAuthenticateUser_thenRetrieveFromDb () {
43+ public void givenExistingUser_whenAuthenticate_thenRetrieveFromDb () {
4044 try {
4145 MyUserDto userDTO = new MyUserDto ();
4246 userDTO .setUsername (USERNAME );
@@ -55,5 +59,27 @@ public void whenAuthenticateUser_thenRetrieveFromDb() {
5559 myUserService .removeUserByUsername (USERNAME );
5660 }
5761 }
62+
63+ @ Test (expected = BadCredentialsException .class )
64+ public void givenIncorrectUser_whenAuthenticate_thenBadCredentialsException () {
65+ try {
66+ MyUserDto userDTO = new MyUserDto ();
67+ userDTO .setUsername (USERNAME );
68+ userDTO .setPassword (PASSWORD );
69+
70+ try {
71+ myUserService .registerNewUserAccount (userDTO );
72+ }
73+ catch (Exception exc ) {
74+ LOG .log (Level .SEVERE , "Error creating account" );
75+ }
76+
77+ UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken (USERNAME2 , PASSWORD );
78+ Authentication authentication = authenticationProvider .authenticate (auth );
79+ }
80+ finally {
81+ myUserService .removeUserByUsername (USERNAME );
82+ }
83+ }
5884
5985}
0 commit comments