Spaces:
Running
Running
File size: 2,629 Bytes
dc510b0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | package com.erp.system.controller;
import org.hibernate.exception.JDBCConnectionException;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.transaction.CannotCreateTransactionException;
import java.net.UnknownHostException;
import java.sql.SQLException;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class GlobalExceptionHandlerTest {
private final GlobalExceptionHandler handler = new GlobalExceptionHandler();
@Test
public void testHandleCannotCreateTransactionException() {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/api/erp/postgres");
UnknownHostException uhe = new UnknownHostException("pg-dc4be3e-binabose955-e13a.d.aivencloud.com");
SQLException sqlEx = new SQLException("Connection failed", "08001", uhe);
JDBCConnectionException jdbcEx = new JDBCConnectionException("Unable to acquire JDBC connection", sqlEx);
CannotCreateTransactionException ex = new CannotCreateTransactionException("Could not open JPA EntityManager for transaction", jdbcEx);
ResponseEntity<Map<String, Object>> response = handler.handleDatabaseConnectivityFailure(ex, request);
assertEquals(HttpStatus.SERVICE_UNAVAILABLE, response.getStatusCode());
assertNotNull(response.getBody());
assertEquals(503, response.getBody().get("status"));
assertEquals("Service Unavailable", response.getBody().get("error"));
assertTrue(response.getBody().get("diagnostic").toString().contains("DNS resolution failure"));
assertTrue(response.getBody().get("diagnostic").toString().contains("pg-dc4be3e-binabose955-e13a.d.aivencloud.com"));
}
@Test
public void testHandleJdbcConnectionException() {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/api/erp/mysql");
SQLException sqlEx = new SQLException("Connection timed out", "08001");
JDBCConnectionException jdbcEx = new JDBCConnectionException("Connection timeout", sqlEx);
ResponseEntity<Map<String, Object>> response = handler.handleDatabaseConnectivityFailure(jdbcEx, request);
assertEquals(HttpStatus.SERVICE_UNAVAILABLE, response.getStatusCode());
assertNotNull(response.getBody());
assertEquals(503, response.getBody().get("status"));
}
}
|