99import org .junit .runner .RunWith ;
1010import org .springframework .beans .factory .annotation .Autowired ;
1111import org .springframework .boot .test .SpringApplicationConfiguration ;
12+ import org .springframework .data .jpa .repository .config .EnableJpaRepositories ;
1213import org .springframework .security .authentication .AuthenticationProvider ;
1314import org .springframework .security .authentication .BadCredentialsException ;
1415import org .springframework .security .authentication .UsernamePasswordAuthenticationToken ;
16+ import org .springframework .security .crypto .password .PasswordEncoder ;
1517import org .springframework .security .core .Authentication ;
1618import org .springframework .test .context .junit4 .SpringJUnit4ClassRunner ;
1719import org .springframework .test .context .web .WebAppConfiguration ;
@@ -36,13 +38,16 @@ public class CustomUserDetailsServiceTest {
3638
3739 @ Autowired
3840 AuthenticationProvider authenticationProvider ;
41+
42+ @ Autowired
43+ PasswordEncoder passwordEncoder ;
3944
4045 @ Test
4146 public void givenExistingUser_whenAuthenticate_thenRetrieveFromDb () {
4247 try {
4348 User user = new User ();
4449 user .setUsername (USERNAME );
45- user .setPassword (PASSWORD );
50+ user .setPassword (passwordEncoder . encode ( PASSWORD ) );
4651
4752 myUserRepository .save (user );
4853
@@ -51,31 +56,23 @@ public void givenExistingUser_whenAuthenticate_thenRetrieveFromDb() {
5156
5257 assertEquals (authentication .getName (), USERNAME );
5358
54- } catch (Exception exc ) {
55- LOG .log (Level .SEVERE , "Error creating account" );
5659 } finally {
5760 myUserRepository .removeUserByUsername (USERNAME );
5861 }
5962 }
60-
61- @ Test (expected = BadCredentialsException .class )
63+
64+ @ Test (expected = BadCredentialsException .class )
6265 public void givenIncorrectUser_whenAuthenticate_thenBadCredentialsException () {
6366 try {
6467 User user = new User ();
6568 user .setUsername (USERNAME );
66- user .setPassword (PASSWORD );
67-
68- try {
69- myUserRepository .save (user );
70- }
71- catch (Exception exc ) {
72- LOG .log (Level .SEVERE , "Error creating account" );
73- }
74-
69+ user .setPassword (passwordEncoder .encode (PASSWORD ));
70+
71+ myUserRepository .save (user );
72+
7573 UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken (USERNAME2 , PASSWORD );
76- Authentication authentication = authenticationProvider .authenticate (auth );
77- }
78- finally {
74+ authenticationProvider .authenticate (auth );
75+ } finally {
7976 myUserRepository .removeUserByUsername (USERNAME );
8077 }
8178 }
0 commit comments