package services; import dao.DataAccessException; import dao.Database; import dao.UserDAO; import model.User; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import request.LoginRequest; import result.LoginResult; import static org.junit.jupiter.api.Assertions.*; public class LoginServiceTest { private Database db; UserDAO uDao; @BeforeEach public void setUp() throws DataAccessException { db = new Database(); db.openConnection(); db.clearTables(); db.closeConnection(true); } @AfterEach public void tearDown() throws DataAccessException { db.openConnection(); db.clearTables(); db.closeConnection(true); } /** * Logs in a user that is registered in the database * @throws DataAccessException */ @Test public void loginServicePass() throws DataAccessException { //Creating new user and adding him to the database User user = new User("JohnA", "subway", "ja@gmail.com", "John", "Allen", "m", "abc123"); uDao = new UserDAO(db.getConnection()); uDao.createUser(user); db.closeConnection(true); //Testing the login service LoginService lService = new LoginService(); LoginRequest request = new LoginRequest("JohnA", "subway"); LoginResult lResult = lService.login(request); assertNotNull(lResult.getAuthToken()); assertEquals(lResult.getUsername(), request.getUsername()); assertNotNull(lResult.getPersonID()); assertTrue(lResult.isSuccess()); } /** * Attempts to log in a user with an incorrect username * @throws DataAccessException */ @Test public void loginServiceFailUsername() throws DataAccessException { //Creating new user and adding him to the database User user = new User("JohnA", "subway", "ja@gmail.com", "John", "Allen", "m", "abc123"); uDao = new UserDAO(db.getConnection()); uDao.createUser(user); db.closeConnection(true); //Testing the login service, this time giving an incorrect username LoginService lService = new LoginService(); LoginRequest request = new LoginRequest("JohnB", "subway"); LoginResult lResult = lService.login(request); assertTrue(lResult.getMessage().contains("Error:")); assertFalse(lResult.isSuccess()); } /** * Attempts to log in a user with an incorrect password * @throws DataAccessException */ @Test public void loginServiceFailPassword() throws DataAccessException { //Creating new user and adding him to the database User user = new User("JohnA", "subway", "ja@gmail.com", "John", "Allen", "m", "abc123"); uDao = new UserDAO(db.getConnection()); uDao.createUser(user); db.closeConnection(true); //Testing the login service, this time giving an incorrect username LoginService lService = new LoginService(); LoginRequest request = new LoginRequest("JohnA", "wrongpass"); LoginResult lResult = lService.login(request); assertTrue(lResult.getMessage().contains("Error:")); assertFalse(lResult.isSuccess()); } }