add failed authentication test

This commit is contained in:
Loredana Crusoveanu 2016-09-28 10:35:21 -04:00
parent 9226fdc110
commit e5302d4e75
1 changed files with 27 additions and 1 deletions

View File

@ -9,9 +9,12 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import static org.junit.Assert.*;
@ -28,6 +31,7 @@ public class CustomUserDetailsServiceTest {
public static final String USERNAME = "user";
public static final String PASSWORD = "pass";
public static final String USERNAME2 = "user2";
@Autowired
MyUserService myUserService;
@ -36,7 +40,7 @@ public class CustomUserDetailsServiceTest {
AuthenticationProvider authenticationProvider;
@Test
public void whenAuthenticateUser_thenRetrieveFromDb() {
public void givenExistingUser_whenAuthenticate_thenRetrieveFromDb() {
try {
MyUserDto userDTO = new MyUserDto();
userDTO.setUsername(USERNAME);
@ -55,5 +59,27 @@ public class CustomUserDetailsServiceTest {
myUserService.removeUserByUsername(USERNAME);
}
}
@Test (expected = BadCredentialsException.class)
public void givenIncorrectUser_whenAuthenticate_thenBadCredentialsException() {
try {
MyUserDto userDTO = new MyUserDto();
userDTO.setUsername(USERNAME);
userDTO.setPassword(PASSWORD);
try {
myUserService.registerNewUserAccount(userDTO);
}
catch (Exception exc) {
LOG.log(Level.SEVERE, "Error creating account");
}
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME2, PASSWORD);
Authentication authentication = authenticationProvider.authenticate(auth);
}
finally {
myUserService.removeUserByUsername(USERNAME);
}
}
}