net.sf.jdbcwrappers.spring.SpringTest.java Source code

Java tutorial

Introduction

Here is the source code for net.sf.jdbcwrappers.spring.SpringTest.java

Source

/*
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package net.sf.jdbcwrappers.spring;

import static org.junit.Assert.assertTrue;

import java.io.File;
import java.lang.reflect.Proxy;
import java.sql.SQLException;

import javax.sql.DataSource;

import net.sf.jdbcwrappers.trim.TrimmingDelegateInvocationHandler;

import org.apache.commons.io.FileUtils;
import org.apache.derby.jdbc.EmbeddedDataSource;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringTest {
    private static EmbeddedDataSource dataSource;

    @BeforeClass
    public static void createDataSource() throws Exception {
        FileUtils.deleteDirectory(new File("target/testDB"));
        dataSource = new EmbeddedDataSource();
        dataSource.setDatabaseName("target/testDB");
        dataSource.setUser("test");
        dataSource.setCreateDatabase("create");
        // Need to request at least one connection for the database to be created
        dataSource.getConnection().close();
    }

    @AfterClass
    public static void destroyDataSource() throws Exception {
        dataSource.setShutdownDatabase("shutdown");
        try {
            dataSource.getConnection();
        } catch (SQLException ex) {
            // This always throws an exception; just continue
        }
        FileUtils.deleteDirectory(new File("target/testDB"));
    }

    @Test
    public void test() throws Exception {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                "net/sf/jdbcwrappers/spring/beans.xml");
        try {
            DataSource ds = (DataSource) context.getBean("dataSource");
            assertTrue(Proxy.getInvocationHandler(ds) instanceof TrimmingDelegateInvocationHandler);
            // Attempt to get a connection
            ds.getConnection().close();
        } finally {
            context.close();
        }
    }
}