Package com.evasion.plugin.junit.persistence

Source Code of com.evasion.plugin.junit.persistence.AbstractPersistentTest

package com.evasion.plugin.junit.persistence;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import org.dbunit.DatabaseUnitException;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.DefaultDataSet;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSetBuilder;
import org.dbunit.operation.DatabaseOperation;
import org.eclipse.persistence.internal.jpa.EntityManagerImpl;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author sebastien.glon
*/
public abstract class AbstractPersistentTest {

    private static final Logger LOGGER =
            LoggerFactory.getLogger(AbstractPersistentTest.class);

    /** Suffixe pour les fichiers DBUnit */
    private static final String DATASET_FILENAME_SUFFIX = "-dataset.xml";
    // ======================================
    // =             Attributes             =
    // ======================================

    protected static EntityManagerFactory emf;

    protected static EntityManager em;

    protected static EntityTransaction tx;

    private static IDatabaseConnection connection;

    private IDataSet dataSet;
    // ======================================
    // =          Lifecycle Methods         =
    // ======================================

    @BeforeClass
    public static void initEntityManager() throws Exception {
        LOGGER.debug("Init entity manager and conntection to DBUnit ");
        emf = Persistence.createEntityManagerFactory("autreTestPU");
        Assert.assertNotNull("Entity Persistence unit File not found (autreTestPU)", emf);
        em = emf.createEntityManager();

        // Initializes DBUnit
        connection = new DatabaseConnection((Connection) ((EntityManagerImpl) (em.getDelegate())).getServerSession().getAccessor().getConnection());
        Assert.assertNotNull("Connection for DBUnit can not be create.", connection);
    }

    @AfterClass
    public static void closeEntityManager() throws SQLException {
        em.close();
        emf.close();
        connection.close();
    }

    @Before
    public void cleanDB() {
        try {
            // Cleans the database with DbUnit
            if (dataSet == null) {
                loadDataSet();
            }
           // Assert.assertNotNull("DataSet DBUnit not initialiszed.", dataSet);
            LOGGER.debug("Chargement du jeux de données de test.");
            DatabaseOperation.CLEAN_INSERT.execute(connection, dataSet);
        } catch (DatabaseUnitException ex) {
            Assert.fail("Error on exec DBUnit" + ex);
        } catch (SQLException ex) {
            Assert.fail("Error SQL on exec DBUnit" + ex);
        }
    }

    @Before
    public void initTransaction() {
        tx = em.getTransaction();
    }

    /**
     * Returns the DBUnit DataSet for this test. By default it searches in the
     * classpath for a file named : <code>&lt;ClassName&gt;-dataset.xml</code>.
     *
     * @return the DBUnit dataSet for this test, or null if no dataSet is used.
     * @throws Exception
     *             in case of an error.
     */
    private void loadDataSet() {
        final String dataSetFileName = getDataSetFilename();
        final URL url = ClassLoader.getSystemResource(dataSetFileName);
        if (url == null) {
            LOGGER.warn("File dataSet {} can not be found.", dataSetFileName);
            dataSet = new DefaultDataSet();
        } else {
            final String urlFile = url.getFile();
            final File file = new File(urlFile);
            LOGGER.debug("Chargement du dataset File : {}", dataSetFileName);
            dataSet = getXmlDataSet(file);
        }
    }

    /**
     * Methode retournant le XMLDataSet sous forme de flat A surcharger pour
     * changer de type de fichier
     *
     * @param file
     *            le fichier XML
     * @return le XML Data Set
     * @throws DataSetException
     *             si il y a une erreur sur le dataSet
     * @throws IOException
     *             si il y a une erreur au niveau de la lecture du fichier
     */
    private IDataSet getXmlDataSet(File file) {
        try {
            return new FlatXmlDataSetBuilder().build(file);
        } catch (MalformedURLException ex) {
            Assert.assertNotNull("Error on File DataSet. " + ex);
        } catch (DataSetException ex) {
            Assert.fail("Error on execute dataset. " + ex);
        }
        return null;
    }

    /**
     * Retourne le nom du fichier DataSet.
     *
     * @return le nom du fichier
     */
    private String getDataSetFilename() {
        return new StringBuilder().append(getClass().getSimpleName()).append(DATASET_FILENAME_SUFFIX).toString();
    }
}
TOP

Related Classes of com.evasion.plugin.junit.persistence.AbstractPersistentTest

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.