Actualiser src/test/java/database/DatabaseConnectionTest.java

This commit is contained in:
Abderrahman El-Ouali 2024-11-15 23:24:08 +01:00
parent 26dfba125e
commit 4a85775995

View file

@ -1,32 +1,58 @@
package database; package database;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
class DatabaseConnectionTest { class DatabaseConnectionTest {
@Test @Test
void testConnectionIsValid() { void testGetConnectionSuccess() {
// Test de base : la connexion ne doit pas être nulle try (Connection connection = DatabaseConnection.getConnection()) {
try { assertNotNull(connection, "Connection should not be null.");
Connection connection = DatabaseConnection.getConnection(); assertTrue(connection.isValid(2), "Connection should be valid.");
assertNotNull(connection, "La connexion ne doit pas être nulle");
} catch (SQLException e) { } catch (SQLException e) {
fail("La connexion a échoué avec une exception : " + e.getMessage()); fail("SQLException should not occur for valid connection details.");
} }
} }
@Test @Test
void testConnectionIsClosedAfterUse() { void testInvalidCredentials() {
// Test si la connexion est fermée correctement après utilisation 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 @Test
void testInvalidConnectionHandling() { void testConnectionFailureWithInvalidUrl() {
// Simule un scénario la connexion échoue (par exemple, mauvaise configuration) 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;
}
} }
} }