测试到数据库的连接

时间:2019-10-20 06:02:54

标签: java oracle jdbc connection spring-test

我要进行测试以检查与数据库的连接。

当我需要测试到另一个数据库的连接时,我在application.properties的 test / resources 中创建了一个对象,然后指出需要用于连接到另一个数据库的属性。

    @SpringBootTest
    @RunWith(SpringRunner.class)
    public class ConnectionToDatabaseTest {

        private static final String MESSAGE= "An url fot connection pool : ";

        private static final String MESSAGE_TIMEOUT = "The database closed the connection before the set time.";

        private final TIMEOUT_SEC= 2;

        private static final Logger LOGGER = LoggerFactory.getLogger(ConnectionToDatabaseTest.class);
        private static final String LOGGER_MESSAGE = "\n An error occurred while getting a database connection : /n";


        @Value("${spring.datasource.driver-class-name}")
        private String driverName;

        @Value("${spring.datasource.url}")
        private String urlToDataBase;

        @Value("${spring.datasource.username}")
        private String userName;

        @Value("${spring.datasource.password}")
        private String password;

        @Test
        public void test(){

            DataSource dataSource = getDataSource();


            try (Connection connection = dataSource.getConnection()) {

                DatabaseMetaData metaData = connection.getMetaData();

                String url = metaData.getURL();
                assertNotNull(url);

                String userName = metaData.getUserName();
                assertNotNull(userName);

                boolean connectionValid = connection.isValid(TIMEOUT_SEC);
                assertTrue(MESSAGE_TIMEOUT, connectionValid);

                outputLogInfo(LOGGER, MESSAGE + url);

            } catch ( Exception e){

                outputLogInfo(LOGGER, LOGGER_MESSAGE + e);
                throw new RuntimeException(e);

            }
        }

        private DriverManagerDataSource getDataSource() {

            DriverManagerDataSource dataSource = new DriverManagerDataSource();

            dataSource.setDriverClassName(this.driverName);

            dataSource.setUrl(this.urlToDataBase);

            dataSource.setUsername(this.userName);

            dataSource.setPassword(this.password);

            return dataSource;

        }
    }

足够了,谁对测试有任何想法和其他变体?

0 个答案:

没有答案