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;
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 testConnectionIsValid() {
// Test de base : la connexion ne doit pas être nulle
try {
Connection connection = DatabaseConnection.getConnection();
assertNotNull(connection, "La connexion ne doit pas être nulle");
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("La connexion a échoué avec une exception : " + e.getMessage());
fail("SQLException should not occur for valid connection details.");
}
}
@Test
void testConnectionIsClosedAfterUse() {
// Test si la connexion est fermée correctement après utilisation
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 testInvalidConnectionHandling() {
// Simule un scénario la connexion échoue (par exemple, mauvaise configuration)
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;
}
}
}