PDLA_24/src/test/java/database/DatabaseConnectionTest.java

58 lines
2 KiB
Java

package database;
import org.junit.jupiter.api.Test;
import java.sql.Connection;
import java.sql.SQLException;
import static org.junit.jupiter.api.Assertions.*;
class DatabaseConnectionTest {
@Test
void testGetConnectionSuccess() {
try (Connection connection = DatabaseConnection.getConnection()) {
assertNotNull(connection, "Connection should not be null.");
assertTrue(connection.isValid(2), "Connection should be valid.");
} catch (SQLException e) {
fail("SQLException should not occur for valid connection details.");
}
}
@Test
void testInvalidCredentials() {
String originalUser = DatabaseConnection.USER;
String originalPassword = DatabaseConnection.PASSWORD;
try {
// Temporarily set invalid credentials
DatabaseConnection.USER = "invalid_user";
DatabaseConnection.PASSWORD = "invalid_password";
SQLException exception = assertThrows(SQLException.class, DatabaseConnection::getConnection, "Expected SQLException due to invalid credentials.");
assertNotNull(exception.getMessage(), "Exception message should not be null for invalid credentials.");
} finally {
// Restore original credentials
DatabaseConnection.USER = originalUser;
DatabaseConnection.PASSWORD = originalPassword;
}
}
@Test
void testConnectionFailureWithInvalidUrl() {
String originalUrl = DatabaseConnection.URL;
try {
// Temporarily set an invalid URL
DatabaseConnection.URL = "jdbc:mysql://invalid_url:3306/test_db";
SQLException exception = assertThrows(SQLException.class, DatabaseConnection::getConnection, "Expected SQLException due to invalid URL.");
assertNotNull(exception.getMessage(), "Exception message should not be null for invalid URL.");
} finally {
// Restore the original URL
DatabaseConnection.URL = originalUrl;
}
}
}